Why all elements of my list seems to be the same?

前端 未结 2 699
忘了有多久
忘了有多久 2021-01-22 09:53

I have the following code:

Integer[] lastExchange = new Integer[nColors];
Integer[] newExchange = new Integer[nColors];
while (true) {
    ...
    for (int i=0;          


        
2条回答
  •  日久生厌
    2021-01-22 10:01

    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

    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]);
    }
    

提交回复
热议问题