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?

有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top