How to fill an array with objects from another array (Java)

I am trying to use an array of 52 objects (Cards with suits and values) and create an array that contains the same 52 objects, but multiple times. (As if I had multiple 52 card decks in one big deck.)

My default constructor populating a single deck array looks like this:

public Deck() {
  allocateMasterPack(); //creates and fills the "model" deck
  cards = new Card[masterPack.length];
  for (int i = 0; i < masterPack.length; i++) {
     cards[i] = new Card(masterPack[i]);
  }

      

How can I do this to fill an array of two decks (104 cards, 52 card deck repeated twice) or three or four?

+3


source to share


3 answers


In Java 8, you can do this using Stream.flatMap()

:

int n = 2;
Card[] cards = IntStream.range(0, n)  // repeat n times
                        .mapToObj(i -> masterPack) // replace each i with the masterPack
                        .flatMap(pack -> Arrays.stream(pack)) // turn the Stream<Card[]> into a Stream<Card> by flattening it
                        .toArray(Card[]::new); // create a new array containing all the cards repeated n times

      

If you cannot use Java 8, you can use System.arraycopy()

:

arraycopy(Object src, int srcPos, Object dest, int destPos, int length)

      

Parameters:
src - source array.

srcPos is the starting position in the original array.
dest is the target array.

destPos is the starting position in the destination data.

length is the number of array elements to copy.

For example, if you want to copy masterPack

to a new deck at twice its size, you can do:



int n = 2;
Card[] cards = new Card[masterPack.length * n];
for (int i = 0; i < n; i++) {
    System.arraycopy(masterPack, 0, cards, i * masterPack.length, masterPack.length);
}

      

This will loop twice by doing:

System.arraycopy(masterPack, 0, cards, 0, 52);
System.arraycopy(masterPack, 0, cards, 52, 52);

      

The first iteration will copy the elements masterPack

at positions 0 through 51 and the second iteration at positions 52-103 in the array cards

.

Your objects Card

should probably be immutable, so there is no need to create new copies Card

every time. The reference to the same 52 objects should be faster and less memory.

+4


source


int repetitions;

for(int i = 0 ; i < masterPack.length * repetitions ; i++)
     cards[i] = new card(masterPack[i % masterPack.length]);

      



+3


source


Try using ArrayList for your card game.

public Deck() {
int repetitions;     
ArrayList<Card> cards = new ArrayList<Card>();

for (int x = 0; x < repititions; x++)
    for (int i = 0; i < masterPack.length; i++) 
        cards.add(new Card(masterPack[i]));

      

+1


source







All Articles