Posted By:
Nick_Maiorano
Posted On:
Thursday, June 5, 2003 07:00 PM
Toni,
If you need deep copying, then not only must the collection be clonable but the elements inside the collection and the elements within the elements. Since you can put any type of object inside collections, this is a tricky proposition. Calling clone() on each element isn't good enough because you don't know if the clone() methods in the elements themselves are implemented with deep copying or not.
There is an easy way out. Use in-memory serialization/de-serialization. You serialize an object then de-serialize right away. This way, you are absolutely sure that everything gets deep-copied. Here's how:
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(sourceObject);
byte[] bytes = bos.toByteArray();
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bis);
Object deepCopiedObject = ois.readObject();
Tada! deepCopiedObject is now a deep copy of sourceObject. But like all other quick solutions in life, it comes with a price: it will perform slowly.