Copy constructor of Array List

蓝咒 提交于 2020-01-30 13:18:23

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!