java - 将值添加到 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 的引用?
解决方案
对于诸如此类的对象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
推荐阅读
- angular - StaticInjectorErro(AppModule) [ScrollableView -> Table]:没有表提供程序
- vue.js - 无法下载 repo vuetifyjs/webpack:响应码 404(未找到)
- css - css 选择所有内容,但忽略特定的父级及其所有子级
- java - 当成员是 java.util.List 类型时序列化 Sonarqube 问题
- c# - 如何使用 C#、SQL Server 在数据库中输入 SELECTED 复选框值?
- python - while 循环不会在抛出垃圾值时重复自身
- tfs - 将 vs 代码连接到本地服务器上的 tfs
- jquery - 我如何在子 iframe 中调用 jquery html() 打印的 java 脚本函数?
- c# - Xamarin Forms Android 应用程序在 Visual Studio 2017 Pro 中共享资源?
- ios - xcode 10 中缺少源代码管理中的配置选项