Reputation: 420
I have an arraylist that looks like:
private ArrayList<ArrayList<Integer>> matrix = new ArrayList<ArrayList<Integer>>(9);
It is filled with these elements:
[[7], [1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 5, 6, 7, 8, 9], [3], [1, 2, 3, 4, 5, 6, 7, 8, 9], [4], [1, 2, 3, 4, 5, 6, 7, 8, 9], [9]]
Now i want to remove the "1" from the second index so my wanted output is:
[[7], [2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 5, 6, 7, 8, 9], [3], [1, 2, 3, 4, 5, 6, 7, 8, 9], [4], [1, 2, 3, 4, 5, 6, 7, 8, 9], [9]]
But when I use the remove method in the form:
matrix.get(1).remove(0);
The output is:
[[7], [2, 3, 4, 5, 6, 7, 8, 9], [2, 3, 4, 5, 6, 7, 8, 9], [2, 3, 4, 5, 6, 7, 8, 9], [3], [2, 3, 4, 5, 6, 7, 8, 9], [4], [2, 3, 4, 5, 6, 7, 8, 9], [9]]
You can see that every "1" in all the ArrayLists of the main ArrayList is removed, instead of only at the second index. How can I change my code so only the "1" of the second index is removed?
Upvotes: 1
Views: 124
Reputation: 41188
You are running into the difference between references and instances here.
When you added the child ArrayList
s into the first one what you actually do is store a reference into the list, that reference then points to an ArrayList
.
Note that its even legal (but definitely not recommended) for an ArrayList
with the right type specified (for example ArrayList<?>
) to have a reference to itself inserted into the list!
If you store the same ArrayList
multiple times then it will copy and create multiple references but those references will still point to the same Object.
You need to create a new ArrayList
(using new
or something like clone()
in order to create the child ArrayLists
and then add the new lists into the original.
Upvotes: 0
Reputation: 13960
Probably matrix
contains several references to the same ArrayList
(containing [1, 2, 3, 4, 5, 6, 7, 8, 9]).
Upvotes: 2
Reputation: 10163
This is because you store the same ArrayList
instance in outer ArrayList
:
outerList = [instance1, instance2, instance2, instance2, ...]
When you delete 1st element from instance2, change is visible in all other indexes.
If you want to avoid these issue, you should create new instance for every sub-list and copy elements from original list.
Upvotes: 2