我有一个包含自定义对象的列表。我想创建该列表的深拷贝。 这是自定义对象的类:
public class MyMemo {
private List<Uri> imageUriList;
private String commentText;
public MyMemo(){
imageUriList = new ArrayList<>();
}
public List<Uri> getImageUriList() {
return imageUriList;
}
public void setImageUriList(List<Uri> imageUriList) {
this.imageUriList = imageUriList;
}
public String getCommentText() {
return commentText;
}
public void setCommentText(String commentText) {
this.commentText = commentText;
}
}
现在我有以下情况:
List<MyMemo> parentList = new ArrayList<>();
List<MyMemo> copyList = new ArrayList<>(parentList);
parentList.get(currentMemoPosition).getImageUriList().removeAll(someOtherList.getImageUriList());
Log.e(TAG,"Total List: "+parentList.get(currentMemoPosition).getImageUriList().size()+" "+copyList.get(currentMemoPosition).getImageUriList().size());
但是如果我对 parentList
进行任何更改,即从中删除
一个项目或向其中添加
新项目。 copyList
也会受到影响。我怎样才能确保 copyList 没有引用相同的内存地址。
更新:
按照建议使用clone()
。但问题是我的自定义对象中有一个列表。我怎样才能 clone()
它们?
最佳答案
当您创建第一个列表时:
List<MyMemo> parentList = new ArrayList<>();
parentList.add(customObject1);
parentList.add(customObject2);
parentList.add(customObject3);
parentList
是自定义对象的引用列表。
将parentList
的内容复制到copyList
时:
List<MyMemo> copyList = new ArrayList<>(parentList);
copyList
现在包含对与 parentList
相同对象的引用。如果您更改 parentList
中的对象,该对象也会在 copyList
中更改,因为它们是同一个对象。
要创建列表的深拷贝,您需要一种方法来复制您的自定义对象之一。您可以实现复制构造函数或克隆方法:
class CustomObject {
private String item1;
private String item2;
public CustomObject(String item1, String item2) {
this.item1 = item1;
this.item2 = item2;
}
// copy constructor
public CustomObject(CustomObject other) {
this.item1 = other.getItem1();
this.item2 = other.getItem2();
}
// clone
public CustomObject clone() {
CustomObject newObj = new CustomObject(this.getItem1(), this.getItem2());
return newObj;
}
}
然后你可以像这样复制一个对象:
CustomObject newObj = new CustomObject(existingObj);
或者像这样:
CustomObject newObj = existingObj.clone();
现在您可以使用复制构造函数对列表进行深度复制:
List<CustomObject> copyList = new ArrayList<>();
for(CustomObject obj : parentList) {
copyList.add(new CustomObject(obj));
}
或克隆方法:
List<CustomObject> copyList = new ArrayList<>();
for(CustomObject obj : parentList) {
copyList.add(obj.clone());
}
我更喜欢使用复制构造函数。你可以阅读一个good article by Josh Block in Effective Java关于克隆与复制构造函数的使用。
关于java - java中带有自定义对象的列表的深拷贝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48575477/