Question

In java, I'm trying to populate a list with a bunch of different objects. But what is happening is, each time I add another object to the list, all the objects in the list get turned into the same thing.

The code in question:

private static ArrayList<Card> deck = new ArrayList<Card>();

private static void setupDeck(){ 
    for(int i = 0; i < suits; i++){
        for(int j = 0; j < cards; j++){
            deck.add(new Card(i,j));
        }   

    }

}

When

deck.add(new Card(i,j));

gets called ever object already in my list is getting turned into a duplicate of the last object to get added to the list. I get that I'm passing the objects by reference, but I don't understand why. Shouldn't my declaration of

new Card(i,j)

create a new Card object for storage. How do I go about resolving this issue?

Était-ce utile?

La solution

You seem to be over-using "static". If a field is declared static, all instances of the class share the same copy, and so the same value. Check whether the fields you are looking at in the Card class are declared "static", and if so remove it.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top