How can I do a deep clone of an object?

John Zukowski

The default/conventional behavior of clone() is to do a shallow copy. You can either override clone() to do a deep copy or provide a separate method to do a deep clone.

The simplest approach to deep cloning is to use Java serialization, where you serialize and deserialize the object and return the deserialized version. This will be a deep copy/clone, assuming everything in the tree is serializable. If everything is not serializable, you'll have to implement the deep cloning behavior yourself.

Assuming everything is serializable, the following should create a complete deep copy of the current class instance:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
Object deepCopy = ois.readObject();