CM1 CM1 - 2 months ago 7
Java Question

ArrayList<ArrayList>> is backedup by the ArrayList that is being added

I am creating an

ArrayList
of
ArrayList
and adding
ArrayLists
to it. But everytime I make changes to the
ArrayList
, it is being reflected in the
ArrayList<ArrayList>
.

Example:

List<List<String>> list1 = new ArrayList<>();
List<String> list2 = new ArrayList<String>();
list2.add("Cat");
list1.add(list2); //no problem
list2.clear();
list2.add("Dog");
list1.add(list2); //problem! the cat is replaced by two dogs this time!!


How do I make sure that updates to
list2
is not reflected in
list1
?

Answer

Short answer ... replace

list2.clear();

with

list2 = new ArrayList<String>();

The problem is happening because list1.add(list2) adds a reference to list2 to list1. It is NOT making a copy of the list that list2 refers to, at any point. So you end up adding multiple references to the same list object to list1.

This is a consequence of the way that Java argument passing works, and the way that the collection APIs have all been designed to work.

Comments