Why are all the values in my list the same? [closed]

∥☆過路亽.° 提交于 2019-12-13 10:37:22

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/17508098/why-are-all-the-values-in-my-list-the-same

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!