首页 > 解决方案 > 将值添加到 Java 中的列表是否会复制数据或创建引用?

问题描述

我有两个清单:

List<Integer> l1 = new ArrayList<Integer>();

List<List<Integer>> l2 = new ArrayList<List<Integer>>();

我使用 . 在列表 l1 中添加了一些数字l1.add()

然后我将列表 l1 添加到第二个列表 l2(现在是 Arraylist 列表)中,使用l2.add(index, l1).

然后我清除 l1,因为我想做其他计算并创建将再次添加到 l2 的列表。清算是使用完成的l1.clear()。在清除 l1 时,我注意到 l2 也被清除了。是否l2.add()只创建对 l1 的引用?

标签: javalist

解决方案


对于诸如此类的对象ArrayList,当您将它们传递给函数时(例如add此处),您传递了它们地址的副本,因此函数可以工作或保存该地址(例如add此处将其保存在第二个列表中),因此对该对象的任何更改都像clear将反映在第二个列表中,除非您创建一个新列表并将其分配给您的第一个列表(现在它引用另一个地址),但您的第二个列表具有您最后一个列表的地址并继续处理。
例如:

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

推荐阅读