Thursday, March 12, 2009

What is the difference between Shallow Copy and Deep Copy (CoreJava)

Question :What is the difference between Shallow Copy and Deep Copy? (CoreJava)
Answer :Shallow Copy:
If a shallow copy is performed on an object, then it gets copied but its
contained objects are not copied. Also any changes made in the cloned
object is automatically reflected in the shallowed copy object as well. An
example
class Student implements Cloneable
{
public String name;
public String age;
public Student(String name,String address)
{
this.name = name;
this.age = age;
}
public Object clone() throws java.lang.CloneNotSupportedException
{
return this;
}
}
public class ShallowCloneClient
{
public ShallowCloneClient() throws java.lang.CloneNotSupportedException
{
Student st1 = new Student("guddu","22,nagar road");
Student st2 = (Student)st1.clone();
st2.name="new name";
System.out.println(st1.name);
}
public static void main(String args[]) throws
java.lang.CloneNotSupportedException
{
new ShallowCloneClient();
}
}
When you execute the programme, the output will be "new name", this
shows that both st1 and st2 instances are the same, changing one changes
other too.
Deep Copy:
A deep copy occurs when an object is copied along with the objects to
which it refers to are also copied. This occurs only when every object in the
tree is serializable. An example
import java.io.*;
class Student1 implements Cloneable,Serializable
{
public String name;
public String age;
public Student1(String name,String address)
{
this.name = name;
this.age = age;
}
public Object clone() throws java.lang.CloneNotSupportedException
{
try{
ByteArrayOutputStream byteArr = new ByteArrayOutputStream();
ObjectOutputStream objOut = new ObjectOutputStream(byteArr);
objOut.writeObject(this);
ByteArrayInputStream byteArrIn = new
ByteArrayInputStream(byteArr.toByteArray());
ObjectInputStream objIn = new ObjectInputStream(byteArrIn);
return objIn.readObject();
}catch(Exception ex){
ex.printStackTrace();
return null;
}
}
}
public class ShallowCloneClient1
{
public ShallowCloneClient1() throws java.lang.CloneNotSupportedException
{
Student1 st1 = new Student1("guddu","22,nagar road");
Student1 st2 = (Student1)st1.clone();
st2.name="new name";
System.out.println(st1.name);
}
public static void main(String args[]) throws
java.lang.CloneNotSupportedException
{
new ShallowCloneClient1();
}
}
When you execute the programme, the output will be "guddu", this shows
that st1 and st2 instances are different.

No comments: