gpt4 book ai didi

Java - 从旧列表创建新列表,旧列表也被修改

转载 作者:行者123 更新时间:2023-11-29 08:26:10 25 4
gpt4 key购买 nike

<分区>

我使用 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]

如何防止这种行为并保持旧列表不变?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com