我有两个列表:
List<Integer> l1 = new ArrayList<Integer>();
List<List<Integer>> l2 = new ArrayList<List<Integer>>();
我使用 l1.add()
将一些数字添加到我的列表 l1 中.
然后我使用 l2.add(index, l1)
将列表 l1 添加到第二个列表 l2 (现在是 Arraylist 的列表) .
然后我清除 l1,因为我想要进行其他计算并创建将再次添加到 l2 的列表。使用 l1.clear()
完成清除。
在清除 l1 时,我注意到 l2 也被清除。
是l2.add()
仅创建对 l1 的引用?
最佳答案
对于ArrayList
等对象,当您将它们传递给函数时(例如这里的add
),您传递了它们地址的副本,因此函数可以工作或保存该地址(例如此处的add
,将其保存在第二个列表中),因此对该对象的任何更改(例如clear
)都将反射(reflect)在第二个列表上,除非您创建一个新列表并分配它到您的第一个列表(现在它引用另一个地址),但您的第二个列表具有您最后一个列表的地址并对其进行处理。
例如:
List<Integer> list1 = new ArrayList<>();
List<List<Integer> list2 = new ArrayList<>();
list2.add(list1); // list2 contains reference to where list1 points, not to list1 itself.
// so any change on where list1 points, happen for list2 reference too.
list1.add(1); // happen for list2
list1 = new ArrayList<>(); // doesn't happen for list2 because I change the address
// saved in list1 but list2 contains last address and work with last address
list1.add(5);
System.out.println(list2.get(0).get(0)); // print 1
关于java - 在 Java 中向列表中添加值是否会复制数据或创建引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52658633/