This question already has an answer here:
clone method vs copy constructor in java. which one is correct solution. where to use each case?
This question already has an answer here:
clone method vs copy constructor in java. which one is correct solution. where to use each case?
Clone is broken, so dont use it.
Prefer a method that copies the object
Read more http://adtmag.com/articles/2000/01/18/effective-javaeffective-cloning.aspx
Great sadness: neither Cloneable/clone nor a constructor are great solutions: I DON'T WANT TO KNOW THE IMPLEMENTING CLASS!!! (e.g. - I have a Map, which I want copied, using the same hidden MumbleMap implementation) I just want to make a copy, if doing so is supported. But, alas, Cloneable doesn't have the clone method on it, so there is nothing to which you can safely type-cast on which to invoke clone().
Whatever the best "copy object" library out there is, Oracle should make it a standard component of the next Java release (unless it already is, hidden somewhere).
Of course, if more of the library (e.g. - Collections) were immutable, this "copy" task would just go away. But then we would start designing Java programs with things like "class invariants" rather than the verdammt "bean" pattern (make a broken object and mutate until good [enough]).
Have in mind that
clone()
doesn't work out of the box. You will have to implementCloneable
and override theclone()
method making inpublic
.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
Keep in mind that the copy constructor limits the class type to that of the copy constructor. Consider the example:
This doesn't work if
person
could be a subclass ofPerson
(or ifPerson
is an interface). This is the whole point of clone, is that it can can clone the proper type dynamically at runtime (assuming clone is properly implemented).or
Now
person
can be any type ofPerson
assuming thatclone
is properly implemented.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.
clone() was designed with several mistakes (see this question), so it's best to avoid it.
From Effective Java 2nd Edition, Item 11: Override clone judiciously
This book also describes the many advantages copy constructors have over Cloneable/clone.
All standard collections have copy constructors. Use them.