Objects
in Java are referred using reference types, and there is no direct
way to copy the contents of an object into a new object.
The assignment of one reference to another merely creates another reference to the same object. Therefore, a special clone() method exists for all reference types in order to provide a standard mechanism for an object to make a copy of itself. Here are the details you need to know about cloning Java objects.
The assignment of one reference to another merely creates another reference to the same object. Therefore, a special clone() method exists for all reference types in order to provide a standard mechanism for an object to make a copy of itself. Here are the details you need to know about cloning Java objects.
Why create a local copy?
The most probable reason for creating a local copy of an object is because you plan to modify the object, and you don't want to modify the method caller's object. If you decide that you need a local copy, you can perform the operation by using the clone() method of the Object class. The clone() method is defined as protected, but you must redefine it as public in all subclasses that you might want to clone.
For example, the standard library class ArrayList overrides clone(), so you can call clone() for ArrayList, like this:
Code: Java
import java.util.*; class MyInt { private int i; public MyInt(int ii) { i = ii; } public void increment() { i++; } public String toString() { return Integer.toString(i); } } public class Test { public static void main(String[] args) { ArrayList al = new ArrayList(); for(int i = 0; i < 10; i++ ) al.add(new MyInt(i)); ArrayList al1 = (ArrayList)al.clone(); // Increment all al1's elements: for(Iterator e = al1.iterator(); e.hasNext(); ) ((MyInt)e.next()).increment(); } }
The clone() method
produces an Object, which must be recast to the proper type. This
example shows how ArrayList's clone() method does not automatically
try to clone each of the objects that the ArrayList contains -- the
old ArrayList and the cloned ArrayList are aliased to the same
objects. This is often called a shallow copy, since it's only copying
the "surface" portion of an object. The actual object
consists of this "surface," plus all the objects that the
references are pointing to and all the objects those objects are
pointing to, etc. This is often referred to as the "Web of
objects." When you copy the entire mess, it is called a deep
copy.
The Cloneable interface and deep copies
By default, classes in Java do not support cloning; the default implementation of the clone() method throws a CloneNotSupportedException. You should override implementation of the clone() method. Remember that you must make it public and, inside the method, your first action must be super.clone(). Classes that want to allow cloning must implement the marker interface Cloneable. Since the default implementation of Object.clone only performs a shallow copy, classes must also override clone to provide a custom implementation when a deep copy is desired. Basically, if you want to make objects of your class publicly cloneable, you need code like this:
Code: Java
class Test implements Cloneable { ... public Object clone() { try { return super.clone(); } catch( CloneNotSupportedException e ) { return null; } } ... }
If you are happy
with a protected clone, which just blindly copied the raw bits of the
object, you don't need to redefine your own version. However, you
will usually want a public one. (Note: You can't create a private or
default scope clone; you can only increase the visibility when you
override.)
Possible problems and a solution
Since the clone() method is protected, subclasses have to explicitly agree to be cloneable by overriding this protected method with a public method. All of the Collections classes do this. The subclass also has to implement Cloneable for the default cloning mechanism in Object.clone() to work.
If you have an object that you know has a public clone() method, but you don't know the type of the object at compile time, you have problems. For instance, say x is declared as an Object. You can't just call x.clone() because Object.clone() is protected. If Cloneable defined a public clone() method, you could use ((Cloneable) x).clone(), but it doesn't. You either have to enumerate all the classes that you think x could be, or you have to resort to reflection.
Another problem arises when you try deep copying of a complex object. You're assuming that the clone() method of all member object variables also does deep copy; this is too risky of an assumption. You must control the code in all classes, or you must know that all classes involved in deep copy operation do such a copy in the right way.
One solution to these problems is to clone using serialization. Serialization is usually used to send objects off somewhere (such as into a file or over the network) so that somebody else can reconstruct them later. You can abuse serialization to immediately reconstruct the object yourself. If the object is serializable at all, the reconstruction should be a faithful copy. In normal uses of serialisation, the original object is nowhere near a faithful copy; it could be on the other side of the world at the far end of a network connection. You can be sure that changing the copy will have no effect on the original.