Home » Java » Copy constructor of Array List

Copy constructor of Array List

Posted by: admin October 21, 2018 Leave a comment

Questions:

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!

Answers: