Monday, 25 April 2016

Shallow Copy vs. Deep Copy



Shallow Copy

Default cloning functionality provided by Object.clone() method.
It creates a new instance of the same class and copies all the fields to the new instance.
It returns 'Object' type and you need to explicitly cast back to your original object.

Object.clone() is a protected method so cannot be used in all your classes.
 
The class which you want to be cloned :
  • have to implement Cloneable interface or else you will get CloneNotSupportedException
  • override clone() method, using either 
    • its own implementation for copy  
    • at least it should invoke super.clone()
Example 
public class CloningExample implements Cloneable {
    ... 
    public Object clone() {
        try {
            return super.clone();
        } catch (CloneNotSupportedException e) {
            throw new Error("Wont occur as we implemented Cloneable");
        }
    }
}


Shallow copy of ce1 object to ce2
CloningExample ce2 = (CloningExample) ce1.clone();







Deep Copy

To achieve Deep copy, we need to override the clone() method for the classes having non-primitive type members. It requires the member objects to be cloned as well, which is not  done by the default cloning (Shallow copy).

When the copied object contains some other object its references are copied recursively in deep copy.
We have to find workaround to copy the final fields into the copied object.

Example
public class Employee implements Cloneable {
    public Object clone() {
        try {
            return super.clone();
        } catch (CloneNotSupportedException e) {
            throw new Error("Wont occur as we implemented Cloneable");
        }
    }
}

public class CloningExample implements Cloneable {
    Employee emp;
    ...
    public Object deepClone() {
        try {           
            CloningExample copy = (CloningExample)super.clone();
            copy.emp = (Employee) emp.clone();
            return copy;
        } catch (CloneNotSupportedException e) {
            throw new Error("Wont occur as we implemented Cloneable");
        }
    }
}














No comments:

Post a Comment

Note: only a member of this blog may post a comment.