Wednesday 1 February 2017

How many ways you can create deep copy of objects?

Deep copy means copying all the property of the object to other objects that is created in the new memory area of heap.

The newly created object will  not refer the old object reference and it will acts as a replica of old object.

If you modify the content of new objects, those content will not reflect in the old objects.

This is also called as deep cloning of the object.

In java, you can achieve deep copy in 3 ways.


  1. Through new keyword 
  2. Through cloning
  3. Through serialization

1) Through new keyword

In this approach, you can copy all the property of the object by creating new one using new keyword. This is like a normal way of object creation, but make sure that if the object is containing the reference of another object, again do the same new object creation for those references. But its tedious process, you need to copy all the property without missing any references.

For example:- See the below employee, how the deep cloning has been done.

public class Employee {
private String name;
private Integer age;
private Department depart;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Integer getAge() {
return age;
}

public void setAge(Integer age) {
this.age = age;
}

public Department getDepart() {
return depart;
}

public void setDepart(Department depart) {
this.depart = depart;
}

}

public class Department {
private String departName;
private String location;

public String getDepartName() {
return departName;
}

public void setDepartName(String departName) {
this.departName = departName;
}

public String getLocation() {
return location;
}

public void setLocation(String location) {
this.location = location;
}

}


public class DeepCloning {

public static void main(String[] args) {
// object one creation
Department department = new Department();
department.setDepartName("sales");
department.setLocation("new york");
Employee employee = new Employee();
employee.setName("John");
employee.setAge(new Integer(27));
employee.setDepart(department);

// Deep cloning by using new keyword
Employee clonedObject = new Employee();
clonedObject.setName(employee.getName());
clonedObject.setAge(employee.getAge());
Department clonedDepartment = new Department();
clonedDepartment.setDepartName(employee.getDepart().getDepartName());
clonedDepartment.setLocation(employee.getDepart().getLocation());
clonedObject.setDepart(clonedDepartment);

}

}

2) Through cloning

Deep copy also can achieved though cloning by following 2 rule.
  1. Class and its sub class must implement Cloneable interface and should override clone() method.
  2. In clone method, it should copy all the property.
For ex:-


public class Employee implements Cloneable {
private String name;
private Integer age;
private Department depart;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Integer getAge() {
return age;
}

public void setAge(Integer age) {
this.age = age;
}

public Department getDepart() {
return depart;
}

public void setDepart(Department depart) {
this.depart = depart;
}
@Override
public Object clone() throws CloneNotSupportedException {
Employee employee = new Employee();
employee.setAge(this.age);
employee.setName(this.name);
employee.setDepart((Department)this.getDepart().clone());
return employee;
}


public class Department implements Cloneable{
private String departName;
private String location;

public String getDepartName() {
return departName;
}

public void setDepartName(String departName) {
this.departName = departName;
}

public String getLocation() {
return location;
}

public void setLocation(String location) {
this.location = location;
}
public Object clone() throws CloneNotSupportedException {
return (Department) super.clone();
}

}


public class DeepCloning {

public static void main(String[] args) throws CloneNotSupportedException {
// object one creation
Department department = new Department();
department.setDepartName("sales");
department.setLocation("new york");
Employee employee = new Employee();
employee.setName("John");
employee.setAge(new Integer(27));
employee.setDepart(department);
// Deep cloning by using cloning
Employee clonedObject = (Employee)employee.clone();
}
}


2) Through  Serialization

We all know that, serialization is the process of converting object state into stream or bytes, that can be transferred over the network, on the other end it can be de-serialized to convert stream into object again. When it is converting, it creates new object and copying all the content to it.  So this process can be used to do deep cloning.

Make sure that you follow the below rules,
  1. Ensure that all classes in the objects are serializable.
  2. Input and output streams should be created.
  3. Use the input and output streams to create object input and object output streams.
  4. Pass the object that you want to copy to the object output stream.
  5. Read the new object from the object input stream and cast it back to the class of the object you sent.
For example:-

public class SerializableCloner {
static public Object deepCopy(Object oldObj) throws Exception
  {
     ObjectOutputStream oos = null;
     ObjectInputStream ois = null;
     try
     {
        ByteArrayOutputStream bos = 
              new ByteArrayOutputStream(); 
        oos = new ObjectOutputStream(bos); 
        // serialize and pass the object
        oos.writeObject(oldObj);   
        oos.flush();               
        ByteArrayInputStream bin = 
              new ByteArrayInputStream(bos.toByteArray()); 
        ois = new ObjectInputStream(bin);                  
        // return the new object
        return ois.readObject(); 
     }
     catch(Exception e)
     {         
        throw(e);
     }
     finally
     {
        oos.close();
        ois.close();
     }
  }
}


public class DeepCloning {

public static void main(String[] args) throws Exception {
// object one creation
Department department = new Department();
department.setDepartName("sales");
department.setLocation("new york");
Employee employee = new Employee();
employee.setName("John");
employee.setAge(new Integer(27));
employee.setDepart(department);
// Deep cloning by using  serializable
Employee clonedObject =       (Employee)SerializableCloner.deepCopy(employee);

}

}




If you like the above solution . Please share this blog
s