Search code examples
javaarraylistremove-method

ArrayList in Arraylist remove method behavior


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?


Solution

  • 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.