tags:

views:

488

answers:

3
+5  Q: 

Java return copy

In Java, say you have a class that wraps an ArrayList (or any collection) of objects. How would you return one of those objects such that the caller will not see any future changes to the object made in the ArrayList? i.e. you want to return a deep copy of the object, but you don't know if it is cloneable.

+2  A: 

One option is to use serialization. Here's a blog post explaining it:

http://weblogs.java.net/blog/emcmanus/archive/2007/04/cloning_java_ob.html

urini
+3  A: 

Turn that into a spec:
-that objects need to implement an interface in order to be allowed into the collection Something like ArrayList<ICloneable>()

Then you can be assured that you always do a deep copy - the interface should have a method that is guaranteed to return a deep copy.

I think that's the best you can do.

Gishu
+1  A: 

I suppose it is an ovbious answer:

Make a requisite for the classes stored in the collection to be cloneable. You could check that at insertion time or at retrieval time, whatever makes more sense, and throw an exception.

Or if the item is not cloneable, just fail back to the return by reference option.

Sergio Acosta