clone(): ArrayList.clone() I thought does a shallow copy

后端 未结 6 1815
别那么骄傲
别那么骄傲 2020-11-29 05:59
ArrayList a=new ArrayList();
a.add(5);
ArrayList b=(ArrayList)a.clone();
a.add(6);
System.out.println(b.t         


        
6条回答
  •  半阙折子戏
    2020-11-29 06:45

    Shallow Cloning is the default cloning strategy provided by Object.clone() which you are talking about. The clone() method of object class creates a new instance and copy all fields of the Cloneable object to that new instance (either it is primitive or reference). So in the case of reference types only reference bits gets copied to the new instance, therefore, the reference variable of both objects will point to the same object. The example we have seen above is an example of Shallow Cloning.

    Deep Cloning As the name suggest deep cloning means cloning everything from one object to another object. To achieve this we need to trick our clone() method to provide our own cloning strategy. We can do it by implementing Cloneable interface and override clone() method in every reference type we have in our object hierarchy and then call super.clone() and these clone() methods in our object’s clone method.

    But if you look at the clone() method of ArrayList in the source code, you will see it is externally copying v.elementData = Arrays.copyOf(elementData, size); after calling super.clone(), which means clone() of ArrayList deeply copies it content

    public Object clone() {
        try {
            ArrayList v = (ArrayList) super.clone();
            v.elementData = Arrays.copyOf(elementData, size);
            v.modCount = 0;
            return v;
        } catch (CloneNotSupportedException e) {
            // this shouldn't happen, since we are Cloneable
            throw new InternalError(e);
        }
    }
    

    To read more about Cloning and its types like deep cloning and shallow cloning please read Java Cloning and Types of Cloning (Shallow and Deep) in Details with Example

提交回复
热议问题