Monday, June 16, 2008

how to clone an object in Java? what is shallow copying and deep copying?

how to clone an object in Java?

Cloning is a way of creating copies of objects in java.

protected Object clone() throws CloneNotSupportedException

the above method creates and returns a copy of the this object.
i.e classes that implement the Cloneable interface should override Object.clone (which is protected) with a public method.

Note: The Cloneable interface doesnot contain the clone method. It is not possible to clone an object by implementing the clone() method.
Note1: invoking the Object.clone() method on instance that doesnot implementing the Cloneable interface will result in Exception " CloneNotSupportedException"

There are two ways of making copy of objects using Cloning.
1. Shallow copying
2. Deep copying

1.Shallow copying : Shallow copy is a bit-wise copy of an object. A new object is created that has an exact copy of the values in the original object. If any of the fields of the object are references to other objects, just the references are copied. Thus, if the object you are copying contains references to yet other objects, a shallow copy refers to the same subobjects.
2.Deep copying : Deep copy is a complete duplicate copy of an object. If an object has references to other objects, complete new copies of those objects are also made. A deep copy generates a copy not only of the primitive values of the original object, but copies of all subobjects as well, all the way to the bottom. If you need a true, complete copy of the original object, then you will need to implement a full deep copy for the object.
Java supports shallow and deep copy with the Cloneable interface to create copies of objects. To make a clone of a Java object, you declare that an object implements Cloneable, and then provide an override of the clone method of the standard Java Object base class. Implementing Cloneable tells the java compiler that your object is Cloneable. The cloning is actually done by the clone method.

example to shallow and deep copying see here http://forum.java.sun.com/thread.jspa?threadID=487186&messageID=2281852

example program

import java.util.List;
import java.util.LinkedList;
import java.util.Iterator;

public class CloningExample implements Cloneable {

private LinkedList names = new LinkedList();
public CloningExample() {
names.add(”Alex”);
names.add(”Melody”);
names.add(”Jeff”);
}
public String toString() {
StringBuffer sb = new StringBuffer();
Iterator i = names.iterator();
while (i.hasNext()) {
sb.append(”\n\t” + i.next());
}
return sb.toString();
}
public Object clone() {
try {
return super.clone();
} catch (CloneNotSupportedException e) {
throw new Error(”This should not occur since we implement Cloneable”);
}
}
public Object deepClone() {
try {
CloningExample copy = (CloningExample)super.clone();
copy.names = (LinkedList)names.clone();
return copy;
} catch (CloneNotSupportedException e) {
throw new Error(”This should not occur since we implement Cloneable”);
}
}

public boolean equals(Object obj) {

/* is obj reference this object being compared */
if (obj == this) {
return true;
}

/* is obj reference null */
if (obj == null) {
return false;
}

/* Make sure references are of same type */
if (!(this.getClass() == obj.getClass())) {
return false;
} else {
CloningExample tmp = (CloningExample)obj;
if (this.names == tmp.names) {
return true;
} else {
return false;
}
}

}


public static void main(String[] args) {

CloningExample ce1 = new CloningExample();
System.out.println(”\nCloningExample[1]\n” +
“—————–” + ce1);

CloningExample ce2 = (CloningExample)ce1.clone();
System.out.println(”\nCloningExample[2]\n” +
“—————–” + ce2);

System.out.println(”\nCompare Shallow Copy\n” +
“——————–\n” +
“ ce1 == ce2 : ” + (ce1 == ce2) + “\n” +
“ ce1.equals(ce2) : ” + ce1.equals(ce2));

CloningExample ce3 = (CloningExample)ce1.deepClone();
System.out.println(”\nCompare Deep Copy\n” +
“——————–\n” +
“ ce1 == ce3 : ” + (ce1 == ce3) + “\n” +
“ ce1.equals(ce3) : ” + ce1.equals(ce3));

System.out.println();

}

}


** The above program is copied from http://www.idevelopment.info/data/Programming/java/object_oriented_techniques/CloningExample.java this location . please follow
this link to get better explanation.

No comments: