It\'s a bit difficult to implement a deep object copy function. What steps you take to ensure the original object and the cloned one share no reference?
A few people have mentioned using or overriding Object.clone()
. Don't do it. Object.clone()
has some major problems, and its use is discouraged in most cases. Please see Item 11, from "Effective Java" by Joshua Bloch for a complete answer. I believe you can safely use Object.clone()
on primitive type arrays, but apart from that you need to be judicious about properly using and overriding clone.
The schemes that rely on serialization (XML or otherwise) are kludgy.
There is no easy answer here. If you want to deep copy an object you will have to traverse the object graph and copy each child object explicitly via the object's copy constructor or a static factory method that in turn deep copies the child object. Immutables (e.g. String
s) do not need to be copied. As an aside, you should favor immutability for this reason.