Reputation: 2025
I have the following block of code:
ArrayList<Integer> list1 = new ArrayList<Integer>();
ArrayList<Integer> list2 = list1;
// both list1 and list2 are empty arraylists
System.out.println(list1.size()); // prints: 0
list2.add(7);
System.out.println(list1.size()); // prints: 1
How come when I modify list2, list1 is also modified? This is causing ConcurrentModificationException
s in my program. How can I edit list2 without changing list1?
Upvotes: 0
Views: 58
Reputation: 5099
In the Java programming language, the value of variables is only stored for primitive types. For Object (and other classes) the values stored are the reference to the actual object.
In your example, you are just creating a variable list2 whose reference points to the object list1, so it is a different variable but with the same reference value and which points to the same object. This is why when you add an element to the list1, list2 is also affected (it is actually the same list. Just a duplicate reference to it).
In order for you to change this behavior, you need to make list2 be equal to a new ArrayList(), either making it an empty new ArrayList or using the copy-constructor and passing list1 as an argument.
Upvotes: 2
Reputation: 123630
list1
and list2
are two different references that you set to refer to the same object.
If you want two different lists with the same contents, you can make a copy:
ArrayList<Integer> list1 = new ArrayList<Integer>();
ArrayList<Integer> list2 = new ArrayList<Integer>(list1);
Upvotes: 7