BlackDots
BlackDots

Reputation: 41

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

I'm 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 decks of 52 cards in one big deck).

My default constructor filling the array of one deck 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 so that I fill an array of two decks (104 card objects, 52-card deck repeated twice), or three, or four?

Upvotes: 4

Views: 3403

Answers (3)

user4668606
user4668606

Reputation:

int repetitions;

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

Upvotes: 3

Anderson Vieira
Anderson Vieira

Reputation: 9049

In Java 8, you could 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 can't use Java 8, you could use System.arraycopy():

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

Parameters:
src - the source array.
srcPos - starting position in the source array.
dest - the destination array.
destPos - starting position in the destination data.
length - the number of array elements to be copied.

For example, if you wanted to copy the masterPack to a new deck with double its size, you could 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, doing:

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

The first iteration will copy the masterPack elements to positions 0 to 51 and the second iteration to positions 52 to 103 in the cards array.

Your Card objects should probably be immutable, so there is no need to create new Card copies every time. Referencing the same 52 objects should be faster and take less memory.

Upvotes: 5

Chriskaz
Chriskaz

Reputation: 9

Try using an 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]));

Upvotes: 1

Related Questions