为什么我的列表中的所有值一样吗? [英] Why are all the values in my list the same?

查看:121
本文介绍了为什么我的列表中的所有值一样吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,我试图填充一堆不同对象的列表。但正在发生的事情是,我每次另一个对象添加到列表时,列表中的所有对象都被转换为同样的事情。

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.

在code问题:

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));
        }   

    }

}

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?

推荐答案

您似乎是过度使用静态。如果某个字段声明为static,同样的副本,所以同样价值的股份类别所有实例。检查你正在寻找的卡类中的字段是否被声明静态,如果是删除它。

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.

这篇关于为什么我的列表中的所有值一样吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆