我在基于enum
的条件制作对象列表时遇到了一些麻烦。似乎在我完成清单后,清单中的每个项目都等同于最后一个项目。这些Java枚举为什么会更改值?
它是指向同一个对象的不同引用的经典案例,但我不知道如何避免它:
我已经削减下来的东西,就像我可以在保持可读性:
public class Foo {
Digit[] array = new Digit[2];
ArrayList<Foo> foozlets;
Foo() {
array[0] = Digit.ZERO;
foozlets = new ArrayList<Foo>();
}
Foo(Foo old, Digit num) {
this.array = old.array; \\This line is a problem, what should it say?
array[1] = num;
}
public static void main(String[] args) {
Foo f = new Foo();
System.out.println("Initial Foo:");
System.out.println(f);
f.listFoozlets();
}
void listFoozlets() {
for (Digit k : Digit.values()) {
if (k == Digit.TWO || k == Digit.FIVE) {
foozlets.add(new Foo(this, k));
System.out.println("** Foozlet being added **");
Foo foo = new Foo(this, k);
System.out.println(foo);
}
}
System.out.println("** List of Foozlets **");
for (Foo foo : foozlets) {
System.out.println(foo);
}
}
public String toString() {
return array[0].toString() + " " + array[1].toString();
}
}
enum Digit { ZERO, ONE, TWO, THREE, FOUR, FIVE }
这里是输出:
Initial Foo:
ZERO NULL
** Foozlet being added **
ZERO TWO
** Foozlet being added **
ZERO FIVE
** List of Foozlets **
ZERO FIVE
ZERO FIVE
如果有人能解释为什么Foo
上的列表中变化的第一个实例,以及如何我可以做一个不变的名单,我会很感激。
编辑:好吧,我看到现在的问题。在一个真正的,更大的程序中,我有一个更大的数组,当我为列表创建一个新的Foo时,我想保留旧信息。我已经更改了代码,以反映我还想保留其他信息。我该如何做到这一点?
关于你的编辑,你需要得到更具体的关于你的情况,作为明显的答案是克隆数组(正如Jon和我的答案所暗示的那样)。如果数组非常大,那么旧数据和新数据之间的关系是什么?你可能需要完全不同的数据结构才能完成这个工作,但由于我们没有深入了解所存储的数据以及新旧Foos的关系,所以我不能给出任何好的建议。 – Yishai 2009-07-23 13:53:48