lionbear28 lionbear28 - 14 days ago 7
Java Question

shallow copy of arraylist

Hello I'm making a poker game. I know this shallow copy constructor is incorrect but why is it incorrect?

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

for (int type= 0; type<=4; type++){
for (int value=1; value<9; value++){
Card newCard = new Card (value, type);
cards.add(newCard);
}
}

}

public Deck(Deck other) {
ArrayList<Card> cardsCopy = cards;

}

Answer
public Deck(Deck other) {
    ArrayList<Card> cardsCopy  = cards;    
    }   

Here cardsCopy is not related to a Deck instance. It is an isolated variable which will doesn't exist any longer as soon as the constructor has finished its execution.
To have a shallow copy of other Deck, you should assign to the cards field of the copy you are creating, the reference to the cards field from the other instance.

A shallow copy constructor could be :

public Deck(Deck other) {
   cards = other.cards;
}   
Comments