clone method vs copy constructor in java. which one is correct solution. where to use each case?
Clone is broken, so dont use it.
THE CLONE METHOD of the Object class is a somewhat magical method that does what no pure Java method could ever do: It produces an identical copy of its object. It has been present in the primordial Object superclass since the Beta-release days of the Java compiler*; and it, like all ancient magic, requires the appropriate incantation to prevent the spell from unexpectedly backfiring
Prefer a method that copies the object
Foo copyFoo (Foo foo){
Foo f = new Foo();
//for all properties in FOo
f.set(foo.get());
return f;
}
Read more http://adtmag.com/articles/2000/01/18/effective-javaeffective-cloning.aspx
That was discussed here as well: http://stackoverflow.com/questions/2283493/how-can-i-create-a-copy-of-my-data-type-i-created-in-java/2283562#2283562
Have in mind that clone()
doesn't work out of the box. You will have to implement Cloneable
and override the clone()
method making in public
.
There are a few alternatives, which are preferable (since the clone()
method has lots of design issues, as stated in other answers), and the copy-constructor would require manual work:
BeanUtils.cloneBean(original)
creates a shallow clone, like the one created byObject.clone()
. (this class is from commons-beanutils)SerializationUtils.clone(original)
creates a deep clone. (i.e. the whole properties graph is cloned, not only the first level) (from commons-lang), but all classes must implementSerializable
Java Deep Cloning Library offers deep cloning without the need to implement
Serializable
See also: How to properly override clone method?. Cloning is broken in Java, it's so hard to get it right, and even when it does it doesn't really offer much, so it's not really worth the hassle.