为什么我的列表中的所有元素似乎都是相同的?
我有以下代码:
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 循环中)。第一个输出显示我确实向列表中添加了不同的数组。当我在第二个循环中进行双重检查时,我发现交换列表的所有元素都是相同的(它们等于列表的第一个元素)。
有人知道我在这里做错了什么吗?
I have the following code:
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]);
}
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正如 unwind 的答案所述,您在循环的每次迭代中添加对同一数组的引用。您每次都需要创建一个新数组:
或者,如果您只是克隆数组:
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:
Alternatively, if you're just cloning the array:
lastExchange
的类型是什么?如果它是对对象的引用,那么问题可能正是如此;您只需添加对可变对象的相同引用,然后对其进行修改并再次添加。由于第一个循环在(大概)修改对象之前打印对象,因此它打印正确的(不同的)值。
What is the type of
lastExchange
? If it's a reference to an object, the the problem is probably exactly that; you just add the same reference to a mutable object, which is then modified and added again.Since the first loop prints the object before it (presumably) is modified, it prints the proper (different) values.