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 ConcurrentModificationExceptions in my program. How can I edit list2 without changing list1?
list1andlist2are 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: