How to Clone an unknown collection? If we can, how do we find out which clone method to use- Shallow or Deep?
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Toni_N
Posted On:   Thursday, June 5, 2003 01:53 PM

My class constructor accepts generic Collection, for example


			
public MyClass implements Cloneable{
Collection collection;
OtherThings others;
public MyClass(Collection collection) {
this.collection = collection;
...
}
...


public void Clone() {
//HOW DO I CLONE A UNKNOWN COLLECTION
//COLLECTION COULD BE ANYTHING: ARRAYLIST, VECTOR, ...
}
...
}


Thanks,
Toni N

Re: How to Clone an unknown collection? If we can, how do we find out which clone method to use- Shallow or Deep?

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.

About | Sitemap | Contact