为什么列表中的所有元素看起来都一样? [英] Why all elements of my list seems to be the same?
问题描述
我有以下代码:
Integer[] lastExchange = new Integer[nColors];
Integer[] newExchange = new Integer[nColors];
while (true) {
...
for (int i=0; i<nColors; i++) {
lastExchange[i] = newExchange[i];
}
...
exchanges.add(lastExchange);
output.log.fine("Exchange:" + lastExchange[0] + "," + lastExchange[1]);
}
for (Integer[] exchange : exchanges) {
output.log.fine("Exchange:" + exchange[0] + "," + exchange[1]);
}
我有两个输出(一个在while循环中,另一个在for循环中).第一个输出显示我确实向列表中添加了不同的数组.当我在第二个循环中进行仔细检查时,我看到exchange
列表的所有元素都相同(它们等于列表的第一个元素).
I have two outputs (one in the while loop another one in the for loop). The first output shows me that I do add different arrays to the list. While when i do a double check in the second loop I see that all elements of the exchange
list are the same (they are equal to the first element of the list).
有人知道我在做什么错吗?
Does anybody know what I am doing wrong here?
推荐答案
作为解开答案的状态,您需要在循环的每次迭代中添加对同一数组的引用.您每次需要创建一个 new 数组:
As unwind's answer states, you're adding a reference to the same array in every iteration of the loop. You need to create a new array each time:
// It's not clear where newExchange is actually populated
Integer[] newExchange = new Integer[nColors];
while (true) {
Integer[] lastExchange = new Integer[nColors];
...
for (int i=0; i<nColors; i++) {
lastExchange[i] = newExchange[i];
}
...
exchanges.add(lastExchange);
output.log.fine("Exchange:" + lastExchange[0] + "," + lastExchange[1]);
}
或者,如果您只是克隆数组:
Alternatively, if you're just cloning the array:
Integer[] newExchange = new Integer[nColors];
while (true) {
Integer[] lastExchange = newExchange.clone();
...
exchanges.add(lastExchange);
output.log.fine("Exchange:" + lastExchange[0] + "," + lastExchange[1]);
}
这篇关于为什么列表中的所有元素看起来都一样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!