Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Problem With clone() if Object Has a Reference Type Attribute

You might have used the clone() method of Object class to get a Clone of an object.But have you ever faced a problem if your object has reference type attributes? Well, I have, and thats what I am going to discuss in this post.
A class can have two types of class level variables,primitive type (as int,float) and reference type(as List).Here is an example:

class AClass
{
int i; //primitive type
List alist; //reference type
}
For more on types, click here

Well, lets return on the original topic.When we make a clone of an object, the primitive type variables are copied in the new clone object, but for the reference type variables,only the reference is copied, not the original instance.For example, if we create the clone of above class’s object,there will be only one List object, and both object will have a reference to this.Here is what I tried:

public class ClassToClone {
ArrayList list;
public ClassToClone(ArrayList list)
{
this.list=list;
}

protected Object clone()
{
try{
return super.clone();
}
catch(CloneNotSupportedException e)
{
return null;
}
}
}

To test it:
public class TestClone {
public static void main(String args[])
{
ClassToClone c1,c2;
ArrayList arraylist= new ArrayList();
arraylist.add("Hello");
c1= new ClassToClone(arraylist);
c2 = (ClassToClone)c1.clone();
c1.list.add("Hi"); //change contents of the list of c1
System.out.print(c1.list.toString());
System.out.print(c2.list.toString()); // prints the list of both objects
}
}

When you run this program, you will see that on changing the list of c1, list of c2 is also changed and they both have the same content.
To avoid this problem, you have to explicitly clone the reference type variables. In ClassToClone, replace clone() method by this:

protected Object clone()
{
try{
ClassToClone aobj = (ClassToClone)super.clone();
aobj.s = (ArrayList)list.clone();
//explicit call to clone() for arraylist
return aobj;

}
catch(CloneNotSupportedException e)
{
return null;
}
}

Here we have explicitly cloned the arraylist.Now a new list will be created for clone object.Now changes done in c1.list do not reflect in c2.list.You can try this by yourself.But remember,clone() can be called only if the class implements Cloneable interface, otherwise we get CloneNotSupportedException.Here class ArrayList implements this interface.
Here and here is a great article to read on object cloning.


Posted in Java, Java Basics Tagged: clone


This post first appeared on Chirag's Computer Blog | A Dose Of My Technical Knowledge, please read the originial post: here

Share the post

Problem With clone() if Object Has a Reference Type Attribute

×

Subscribe to Chirag's Computer Blog | A Dose Of My Technical Knowledge

Get updates delivered right to your inbox!

Thank you for your subscription

×