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?
This is what happens when you add array list a
to array list j
10 times.
This is what happens when you add 1
to array list a
.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With