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

前端 未结 2 638
灰色年华
灰色年华 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:37

    tempPIX is reference to an int[] array in memory.

    Each time you update the array and add it to the list, you are simply adding the same reference to the same array over and over again.

    A better solution would be to create a new array on each loop...

    int[] tmpAry = new int[2];
    tmpAry[0] = ntempPIX[0] + tempDIR[0];
    tmpAry[1] = tempPIX[1] + tempDIR[1];
    
    tempPIX = tmpAry; // Reassign the reference so the rest of the code doesn't need to be updated
    

    UPDATED from comments

    Well, all I can say is, I don't know what you're doing...

    public class TestArrays {
    
        public static void main(String[] args) {
            List listOfValues = new ArrayList();
            int[] outter = new int[] {1, 2, 3, 4};
    
            listOfValues.add(outter);
            dump(outter);
            for (int index = 0; index < 5; index++) {            
                int[] inner = new int[] {
                    rand(),
                    rand(),
                    rand(),
                    rand()
                };
                outter = inner;
                dump(outter);
                listOfValues.add(outter);            
            }
    
            int index = 0;
            for (int[] values : listOfValues) {
                System.out.print("[" + index + "] ");
                dump(values);
                index++;
            }
    
        }
    
        public static void dump(int[] values) {
            for (int value : values) {
                System.out.print(value + ", ");
            }
            System.out.println("\b\b"); // Cheeck...;)
        }
    
        public static int rand() {
            return (int)Math.round(Math.random() * 100);
        }
    
    }
    

    Which outputs something like...

    1, 2, 3, 4
    44, 35, 76, 9
    44, 11, 17, 35
    99, 24, 39, 23
    20, 31, 9, 66
    45, 50, 60, 27
    [0] 1, 2, 3, 4
    [1] 44, 35, 76, 9
    [2] 44, 11, 17, 35
    [3] 99, 24, 39, 23
    [4] 20, 31, 9, 66
    [5] 45, 50, 60, 27
    

提交回复
热议问题