Amazon Affiliate

Tuesday 27 March 2012

SHALLOW COPY AND DEEP COPY IN JAVA WITH EXAMPLES..


Shallow Copy -        
    Clone can be archived by object.clone() method. It gives the Shallow copy of the object. In this process a new object is created That have all the value and instance variable. And if main object has any references to other object then the references are copied in the shallow copy.

Example -

class A implements Cloneable{
   
    A(String personName, Integer age){
        this.personName=personName;
        this.age=age;
    }
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
    private String personName = null;
    private transient Integer age = null;
   
    public Integer getAge() {
        return age;
    }
    public String getPersonName() {
        return personName;
    }
}

public class Test{
    public static void main(String[] args) throws CloneNotSupportedException {
        A a = new A("Albar", new Integer(50));
        A a1 = (A)a.clone();
        System.out.println(a1.getPersonName());
    }
}

Deep Copy:-
    Deep Copy of any object can be achieved by write the object into byte stream and again deserialize it. It gives the Deep Copy of the object. Deep copy is a totally duplicate copy of an object.
And if main object has any references to other object then the complete new copies of those objects will be available  in the Deep Copy.

Example to get Deep Copy -

class A implements Serializable{
   
    A(String personName, Integer age){
        this.personName=personName;
        this.age=age;
    }
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
    private String personName = null;
    private transient Integer age = null;
   
    public Integer getAge() {
        return age;
    }
    public String getPersonName() {
        return personName;
    }
}

public class Test{
    public static void main(String[] args) throws CloneNotSupportedException {
        try {
            A a = new A("Albar", new Integer(50));
            A deepCopy = null;
            ByteArrayOutputStream bos = new ByteArrayOutputStream();

            ObjectOutputStream out = new ObjectOutputStream(bos);

            out.writeObject(a);
            out.flush();
            out.close();

            ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));
            Object obj = in.readObject();
            deepCopy = (A)obj;
            System.out.println(deepCopy.getPersonName());
            }
            catch(IOException e) {
                e.printStackTrace();
            }
            catch(ClassNotFoundException cnfe) {
                cnfe.printStackTrace();
            }
            }
}

No comments:

Post a Comment