Java ArrayList拷贝构造函数
Java ArrayList copy constructor
我有一个对象 anObject
有两个私有成员变量:
public class anObject {
private String name;
private ArrayList<String> myList = new ArrayList<String>();
}
我有一个构造函数:
public anObject() {
name = "";
}
我有我的复制构造函数:
public anObject(anObject copy) {
this();
newObject(copy);
}
public void newObject(anObject copyTwo) {
name = copyTwo.name;
// How to deep copy an ArrayList?
}
但是我如何 "deep copy" 我的 copyTwo
中 ArrayList 的所有元素到我的 this.myList
?
我看过关于 SO 的其他问题,但他们的 ArrayLists 都包含对象,而我的只包含字符串。感谢您的帮助!
您可以使用新的 collection 进行深度复制。新 collection 中的更改不会影响以前的列表
List<String> copyTwo= new ARrayList<String>();
copyTwo.addAll(myList );
创建对列表的新引用,因为您的列表包含字符串并且字符串是不可变的,您可以这样做:
List<String> copyString = new ArrayList<>(original);
我有一个对象 anObject
有两个私有成员变量:
public class anObject {
private String name;
private ArrayList<String> myList = new ArrayList<String>();
}
我有一个构造函数:
public anObject() {
name = "";
}
我有我的复制构造函数:
public anObject(anObject copy) {
this();
newObject(copy);
}
public void newObject(anObject copyTwo) {
name = copyTwo.name;
// How to deep copy an ArrayList?
}
但是我如何 "deep copy" 我的 copyTwo
中 ArrayList 的所有元素到我的 this.myList
?
我看过关于 SO 的其他问题,但他们的 ArrayLists 都包含对象,而我的只包含字符串。感谢您的帮助!
您可以使用新的 collection 进行深度复制。新 collection 中的更改不会影响以前的列表
List<String> copyTwo= new ARrayList<String>();
copyTwo.addAll(myList );
创建对列表的新引用,因为您的列表包含字符串并且字符串是不可变的,您可以这样做:
List<String> copyString = new ArrayList<>(original);