In terms of "best practices", which methodology is preferred for creating a "deep copy" of an object?
-
Use some cloning library: http://stackoverflow.com/a/1241100/738746 – Bhesh Gurung Dec 27 '11 at 23:54
2 Answers
Use a copy constructor. Cloneable is a straight-up API disaster. See Effective Java Item 10 (Item 11 in the 2nd. ed.).
Item 11: Override
clonejudiciouslyThe
Cloneableinterface was intended as a mixin interface (item 18) for objects to advertise that they permit cloning. Unfortunately, it fails to serve this purpose. Its primary flaw is that it lacks aclonemethod, andObject'sclonemethod is protected. You cannot, without resorting to reflection (Item 53), invoke theclonemethod on an object merely because it implementsCloneable. Even a reflective invocation may fail, as there is no guarantee that the object has an accessibleclonemethod.
-
+1 (for the link, mostly) What about other alternatives to Cloneable, though? (A copy constructor generally requires a known concrete type, which while often is perfectly fine, is different from Cloneable.) – Dec 27 '11 at 23:56
-
1This quote also seems relevant to this question: " In effect, the clone method functions as another constructor; you must ensure that it does no harm to the original object and that it properly establishes invariants on the clone" – AHungerArtist Dec 27 '11 at 23:56
There is nothing wrong with the general idea of a cloneable interface. It is easier than copy constructor for API users .
The problems with Java's Cloneable and Object.clone are not that bad either; they can be overcome with a little effort. And you can always have your own cloneable interface.
Java 8 could fix Cloneable by adding the clone() method with a default implementation
interface Cloneable
public Object clone() default { return Cloneables.defaultClone(this); }
not sure they have any plan to do so.
- 44,725
- 9
- 65
- 93
-
1+1 for a great point about Java 8. Though I think an `UnsupportedOperationException` would be a safer default implementation for objects that haven't explicitly defined clone()..... – mikera Dec 27 '12 at 04:30