<p>In Java, say you have a class that wraps an <code>ArrayList</code> (or any collection) of objects. </p>

<p>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? </p>

<p>i.e. you want to return a deep copy of the object, but you don't know if it is cloneable.</p>

[{'answer_id': 29825, 'author': 'urini', 'author_id': 373, 'author_profile': 'https://Stackoverflow.com/users/373', 'pm_score': 2, 'selected': False, 'text': '<p>One option is to use serialization. Here\'s a blog post explaining it:</p>\n\n<p><a href="http://weblogs.java.net/blog/emcmanus/archive/2007/04/cloning_java_ob.html" rel="nofollow noreferrer">http://weblogs.java.net/blog/emcmanus/archive/2007/04/cloning_java_ob.html</a></p>\n'}, {'answer_id': 29826, 'author': 'Gishu', 'author_id': 1695, 'author_profile': 'https://Stackoverflow.com/users/1695', 'pm_score': 3, 'selected': True, 'text': "<p>Turn that into a spec:<br>\n-that objects need to implement an interface in order to be allowed into the collection\nSomething like <code>ArrayList&lt;ICloneable&gt;()</code></p>\n\n<p>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.  </p>\n\n<p>I think that's the best you can do.  </p>\n"}, {'answer_id': 29828, 'author': 'Sergio Acosta', 'author_id': 2954, 'author_profile': 'https://Stackoverflow.com/users/2954', 'pm_score': 1, 'selected': False, 'text': '<p>I suppose it is an ovbious answer:</p>\n\n<p>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.</p>\n\n<p>Or if the item is not cloneable, just fail back to the return by reference option.</p>\n'}]
['https://Stackoverflow.com/questions/29820', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/142/']