Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding element to 2d arraylist in java

Tags:

java

arraylist

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 every element of j as opposed to only the third element, and what can I do to fix this?

like image 995
Jim Avatar asked Jan 11 '17 07:01

Jim


1 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 array list a.

![enter image description here

So basically all 10 indexes of ArrayList j points to a single ArrayList a. Hence, printing of value from any index of j will always gives you the same result.


To let each index point to a different array list:

enter image description here

like image 164
user3437460 Avatar answered Sep 23 '22 01:09

user3437460