问题
I just read about deep copy of ArrayList, that people think
new ArrayList<>(originalList);
will create a shallow copy. And I wrote a small demo
ArrayList<String> originalNameList = new ArrayList<>(Arrays.asList("Anna", "Betty", "Chris"));
List<String> copyNameList1=originalNameList;
List<String> copyNameList2= new ArrayList<>(originalNameList);
originalNameList.add("Duke");
copyNameList1.add("Ellen");
copyNameList1.set(1,"Bill");
copyNameList2.set(0,"Andy");
System.out.println("originalNameList = " + originalNameList);
System.out.println("copyNameList1 = " + copyNameList1);
System.out.println("copyNameList2 = " + copyNameList2);
The result:
originNameList = [Anna, Bill, Chris, Duke, Ellen]
copyNameList1 = [Anna, Bill, Chris, Duke, Ellen]
copyNameList2 = [Andy, Betty, Chris]
I feel that copy constructor of ArrayList is not that shallow. That why people say that so? Are there some levels of deep copy? Thank a lot!
回答1:
Your definitions for "shallow" and "deep" copy seem to be wrong. It seems like you think a shallow copy means "copying the reference to the object", like this:
List<String> copyNameList1=originalNameList;
Whereas a "deep" copy creates a new array list:
List<String> copyNameList2= new ArrayList<>(originalNameList);
Note that the above is a misconception.
A shallow copy actually means creating a new array list with the same elements, while a deep copy means creating a new array list that has copies of the elements in the original array list.
The big difference here is "whether the elements in the array list are copied".
Imagine you have an array list object a1
. It contains references to 3 three objects obj1
, obj2
, obj3
.
A shallow copy of a1
will create a new array list object a2
that contains references to the same obj1
, obj2
, obj3
objects.
A deep copy of a1
will create a new array list object a2
that contains references to obj4
, obj5
, obj6
, where obj4
, obj5
and obj6
are copies of obj1
, obj2
, and obj3
respectively.
Here are two methods that shows what happens in shallow copy and deep copy:
static ArrayList<String> shallowCopy(ArrayList<String> original) {
ArrayList<String> copy = new ArrayList<>();
for (String s : original) {
copy.add(s);
}
return copy;
}
static ArrayList<String> deepCopy(ArrayList<String> original) {
ArrayList<String> copy = new ArrayList<>();
for (String s : original) {
String copyOfString = new String(s); // note that each string is copied as well
copy.add(copyOfString);
}
return copy;
}
In general, a deep copy copies the objects that the target object refers to as well.
来源:https://stackoverflow.com/questions/51336923/copy-constructor-of-array-list