为什么我的列表中的所有元素似乎都是相同的?

2023-12-03

我有以下代码:

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列表是相同的(它们等于列表的第一个元素)。

有人知道我在这里做错了什么吗?


正如 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]);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么我的列表中的所有元素似乎都是相同的? 的相关文章

随机推荐