我有以下代码:
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
列表的所有元素都是相同的(它们等于列表的第一个元素)。
有人知道我在这里做错了吗?
答案 0 :(得分:5)
正如unwind的回答所述,你在循环的每次迭代中都添加了对同一数组的引用。您需要每次都创建一个 new 数组:
// 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]);
}
或者,如果您只是克隆数组:
Integer[] newExchange = new Integer[nColors];
while (true) {
Integer[] lastExchange = newExchange.clone();
...
exchanges.add(lastExchange);
output.log.fine("Exchange:" + lastExchange[0] + "," + lastExchange[1]);
}
答案 1 :(得分:2)
lastExchange
的类型是什么?如果它是对象的引用,则问题可能正是如此;您只需向可变对象添加相同的引用,然后对其进行修改并再次添加。
由于第一个循环在对象(可能)被修改之前打印对象,因此它会打印正确的(不同的)值。