Home > front end >  How change an element of 2D ArrayList without change all the elements of the column
How change an element of 2D ArrayList without change all the elements of the column

Time:05-19

I want to change the value of an element of the list. I have to tried but I changed all the elements of the column. How can I do this?

My code is this:

    ArrayList<ArrayList<Integer>> matrix = new ArrayList<ArrayList<Integer>>();
    ArrayList<Integer> array = new ArrayList<Integer>();
    for(int i = 0; i < 3;   i){
        array.add(0);
    }
    for(int i = 0; i < 3;   i){
        matrix.add(i,array);
    }

    showMatrix(matrix);
    
    matrix.get(0).set(0,1);
    
    showMatrix(matrix);

Matrix initialized is:

E/Matrix: [[0, 0, 0], [0, 0, 0], [0, 0, 0]]

Matrix change the position [0][0] to 1:

E/Matrix: [[1, 0, 0], [1, 0, 0], [1, 0, 0]]

How can I change only the position[0][0]? And not change [1][0] and [2][0].

Thank you.

CodePudding user response:

problem is with:

for(int i = 0; i < 3;   i){
    matrix.add(i,array);
}

array is instantiated at the start with ArrayList<Integer> array = new ArrayList<Integer>(); and never get instantiated again. That means array always refer to the same object. So, there is always the only copy!

Instead, try:

for(int i = 0; i < 3;   i){
        matrix.add(i, new ArrayList<>(array));
}
  • Related