gpt4 book ai didi

java - 从另一个列表创建一个列表并从复制的列表中删除元素

转载 作者:行者123 更新时间:2023-11-29 03:30:33 24 4
gpt4 key购买 nike

假设我有以下结构并且我创建了一个这样的列表。如果我执行 temp.remove(0) 它不会影响原始列表,但 temp.get(0).vars.remove(0) 将从中删除元素原始列表也是如此。

我认为 new ArrayList(top.mids) 没有做深拷贝那么 temp.remove(0) 怎么不影响原始列表?

//Top class init part and adding elements are omitted
List<Mid> temp = new ArrayList(top.mids);
temp.remove(0);
temp.get(0).bots.remove(0);


public class Top{
List<Mid> mids = new ArrayList<Mid>();
}

public class Mid{
List<Bot> bots = new ArrayList<Bot>();

}

public class Bot{
int id;
}

最佳答案

是的,你的理解是正确的。 List newList = new ArrayList(collection); 将进行浅拷贝。您可以修改 newList 而不会影响原始 collection,但它们将各自引用相同的元素,因此如果您修改一个列表中的一个元素,另一个列表的元素也会得到改变。

这称为浅拷贝。这是我所描述内容的直观表示:

enter image description here

底部的东西是数组中的对象。

关于java - 从另一个列表创建一个列表并从复制的列表中删除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18498622/

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