11 Aralık 2010 Cumartesi

object cloning in java

java objects are manipulated via reference variables, there is no way to copy an object in java directly.. clone() method of Object class is used to provide a standard copying mechanism. clone() returns an Object, so dont forget to recast..
There is also the shallow copy - deep copy issue to deal with.. In shallow copy only the surface portion of the object is copied, as in the case of Arraylist s overrided clone().
A property of shallow copies is that fields that refer to other objects will point to the same objects in both the original and the clone. (http://javatechniques.com/blog/faster-deep-copies-of-java-objects/)
Copying the object entirely is the deep copy..
In order to make a class with the ability of deep copying itself:
  • default clone() implementation throws CloneNotSupportedException (if class is not implementing Cloneable interface)
  • implement Cloneable interface
  • make overrided clone() implementation public and do super.clone() (as in all Collections clone() methods)
  • Object s clone() only makes shallow copy, so write your implementation for a deep copy..

  • public class SampleClass implements Cloneable {
    ...
    public Object clone() throws CloneNotSupportedException {
    return super.clone();
    }
    }

    Serializing and reconstructing when the object is extremely complex, is also a solution to deep copying problem.. Besides, in http://javatechniques.com/blog/faster-deep-copies-of-java-objects/, the code presents a faster way of making deep copy..

    http://www.go4expert.com/forums/showthread.php?t=5424
    http://www.jguru.com/faq/view.jsp?EID=20435 (this is the solution i used, since i have complex serializable objects..)

    Hiç yorum yok:

    Yorum Gönder