6
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?

4 Answers 4

11

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

Sign up to request clarification or add additional context in comments.

1 Comment

Question if you wanted to add a value at the "element" 10x10 meaning the last entry in 'j' and entry 'a'. j.get(9).add(9, <my Int>);
3

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

Comments

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

In your code a is the pointer to the memory location where the ArrayList resides.

Comments

-1

Actually j.get(3) references the arrayList a as every j.get(c), that's why every cells of j pointing on a are changed. the next image shows how it works.illustration

1 Comment

You don't use square brackets for get

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.