Add variables to Arraylist and it replaces all previous elements , while variables are not static

前端 未结 2 611
灰色年华
灰色年华 2021-01-28 16:08

My question is similar to this one Add elements to Arraylist and it replaces all previous elements in Java . Though my variables are not static. Still everytime I add one, the o

2条回答
  •  北恋
    北恋 (楼主)
    2021-01-28 16:33

    Ok, the problem is that you are changing the same array object and pushing a reference to it into the list. So, when the array object is changed, it will also get reflected in all the references pointing it.

    int[] tempPIX = pixelFIRST;
    

    So, you have created this array outside your while loop. And inside the while loop, you are modifying your array and adding to the list. Since, array object are not immutable so, a new array object will not be created when you change the content, rather the change will get reflected in your list also.

    What you can do is, create a new array inside your while loop. And copy the content in that array.

    int[] temp = new int[2];
    temp[0] = tempPIX[0] + tempDIR[0];
    temp[1] = tempPIX[1] + tempDIR[1];
    
    tempPIX = temp;
    

    And add this array to your List. You also need to re-assign the new array to your old array to reflect changes there also (As in the 4th line)

提交回复
热议问题