Adding element in 2d arraylist in java

ArrayList<Integer> a =new ArrayList<Integer>(); ArrayList<ArrayList<Integer>> j =new ArrayList<ArrayList<Integer>>(); a.add(1); a.add(2); a.add(3); for(int c=0; c<10; c++){ j.add(a); } j.get(3).add(1); System.out.println(j); 

Does anyone know why this code adds 1 to each element of j, and not just to the third element, and what can I do to fix this?

+6
source share
4 answers

This is what happens when you add array list a to array list j 10 times. ! [enter image description here

This is what happens when you add 1 to the list of array a .

! [enter image description here

Thus, basically all 10 ArrayList j indices point to one ArrayList a . Therefore, printing a value from any index j will always give you the same result.


So that each pointer points to a different list of arrays:

enter image description here

+11
source

You use the same instance of ArrayList a in each j element. You must create a new ArrayList instance for each j element if you want them to be different.

+3
source
  for(int c=0; c<10; c++) { j.add(new ArrayList<>(a)); } 

In your code a, there is a pointer to the cell in which the ArrayList is located.

+2
source

In fact, j.get (3) refers to an array of List a like every j.get (c), so every cell j pointing to a changes. The following image shows how this works. illustration

-one
source

Source: https://habr.com/ru/post/1013974/


All Articles