I have a List with custom objects. I want to create a deep copy of that List. Here is the class of the custom Object:
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;
}
}
Now I have below situation:
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());
But if I make any change to the parentList
i.e either delete
an item from it or add
new item to it. copyList
is also effected. How can I make sure copyList is not referring the same memory address.
Update:
As suggested to use clone()
. But problem is I have a list in my custom object. How can I clone()
them?
clone
method that will copy each and every element of the source into the destination which shall be the returned value. somewhat like Prototype design pattern.main()
method that shows the problems you have encountered?removeAll()
to alter the inner list of the custom object ofparentList
. But that is also effecting thecopyList
size as well.