为什么原始变量会在新变量发生变化时发生变化?

vca*_*ra1 0 java iteration arraylist concurrentmodification

我有以下代码块:

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
Run Code Online (Sandbox Code Playgroud)

为什么我修改list2时,list1也被修改了?这导致ConcurrentModificationException了我的程序.如何在不更改list1的情况下编辑list2?

tha*_*guy 7

list1并且list2是您设置为引用同一对象的两个不同引用.

如果您想要两个具有相同内容的不同列表,您可以复制:

ArrayList<Integer> list1 = new ArrayList<Integer>();
ArrayList<Integer> list2 = new ArrayList<Integer>(list1);
Run Code Online (Sandbox Code Playgroud)