public interface ILcdDeepCloneable
clone
method is designed to support the cloning of complex Object
graphs with loops. Its purpose is to create a copy of the origin Object graph (all objects reachable from within
the original object), without introducing duplicate clones of an Object.
The precise meaning of 'deep clone' may depend on the Object class.
As a general rule, a deep clone should allow to modify the state of the cloned Object graph, without affecting the
state of the original Object graph.
The following code can be used as a general outline for the deep clone
method:
public Object clone(Map aObjectDictionary) {
MyClass clone = (MyClass) aObjectDictionary.get(this);
if (clone == null) {
// Make new clone of this Object.
clone = (MyClass) super.clone();
// Add clone to the object dictionary.
aObjectDictionary.put(this, clone);
// For each ILcdDeepCloneable field, make a deep clone.
clone.field1 = (MyFieldClass1) field1.clone(aObjectDictionary);
// For other cloneable objects, make a normal clone.
clone.field2 = (MyFieldClass2) field2.clone();
// Primitive fields and immutable Objects do not need to be cloned.
}
return clone;
}
The Object.clone()
can now be overridden as follows:
public Object clone() {
return clone(new IdentityHashMap());
}
Modifier and Type | Method and Description |
---|---|
Object |
clone(Map aObjectDictionary)
Returns a deep clone of this Object.
|
Object clone(Map aObjectDictionary)
java.util.Map
, using reference-equality instead of object-equality when
comparing keys (such as the java.util.IdentityHashMap
). It contains as keys the objects in the original
object graph that have already been cloned, and as values their corresponding clone.
The Object returned by this method should fulfill the following conditions, as specified in
the general Object.clone()
contract:
this.clone(aObjectDictionary) != this
this.clone(aObjectDictionary).getClass() == this.getClass()
this.clone(aObjectDictionary).equals(this)
clone
method is called,
this method shall return that clone:
aObjectDictionary.get(this) == null || aObjectDictionary.get(this) == this.clone(aObjectDictionary)
clone method has completed:
this.clone(aObjectDictionary) == aObjectDictionary.get(this)
aObjectDictionary
- the Object dictionary that keeps track of the objects for which a clone has already been made,
and their corresponding clone Object.NullPointerException
- if aObjectDictionary == null
.