java - Java - 从旧列表创建新列表,旧列表也被修改
问题描述
我已经通过使用方法从旧列表创建了新列表addAll()
,当我尝试修改新列表时,旧列表也被修改了。
例如 -
List<A> list = new ArrayList<A>();
list.add(new A("something1"));
list.add(new A("something2"));
list.add(new A("something3"));
list.add(new A("something4"));
List<A> newList = new ArrayList<A>();
newList.addAll(list);
for(A a1 : newList){
a1.setA("something new");
}
System.out.println("list----------------");
for(A a1 : list){
System.out.println(a1.toString());
}
System.out.println("new list----------------");
for(A a1 : newList){
System.out.println(a1.toString());
}
输出 -
list----------------
A [a=something new]
A [a=something new]
A [a=something new]
A [a=something new]
new list----------------
A [a=something new]
A [a=something new]
A [a=something new]
A [a=something new]
如何防止这种行为并保持旧列表不变?
解决方案
Java 将对象的引用存储在列表中。因此,如果您制作一个副本列表,只有列表对象不同,它仍然使用对 A 对象的相同引用,换句话说,两个列表中都有相同的 A 对象。如果您想防止这种情况发生,您需要制作 A 对象的克隆副本。结果将如下所示:
List<A> newList = list.stream.map(a -> new A(a.getContent()).collect(Collectors.toList());
或者,如果您在 A 中有克隆/复制方法
List<A> newList = list.stream.map(A::clone).collect(Collectors.toList());
推荐阅读
- python - Python在列表奇怪行为中获取元素的排名
- php - Laravel 5.4 动态通知类型
- python-3.x - 与另一个基于 TCL 的程序一起运行 tkinter
- c# - 在实体框架迁移中从复杂对象创建字段时出错
- azure-active-directory - Azure AD B2C - 恢复您的帐户不同于重置密码
- python - 为什么 textvariable tkinter 不写我的文件,
- c# - 使用 caldav 使用 C# UWP 应用从 owncloud 获取日历
- r - Extract the top first row from dataframe in R
- reactjs - 如何用酶、柴测试 HOC
- appium - Appium - 遇到内部错误运行命令:错误:zipAlignApk 失败