Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java return copy to hide future changes

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.

like image 242
Lehane Avatar asked Aug 27 '08 09:08

Lehane


2 Answers

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.

like image 167
Gishu Avatar answered Sep 25 '22 21:09

Gishu


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

like image 33
urini Avatar answered Sep 24 '22 21:09

urini