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(lastExchan开发者_如何转开发ge);
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?
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]);
}
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.
精彩评论