There is no standard way to have an implementation of any Collection that automatically clones its objects as they are added.
If you really wanted to, you could create your own List implementation and use reflection to clone each object that goes in and out. When a question like this is asked, I never recommend that you actually create your own implementation of something in the Collections library. I think the only reason to actually create your own implementation in this case, would be if you have some other library that takes a List or Collection as a parameter and you really don't want the values of that Collection to be mutated.
There's also the option of not actually storing mutable data in a list. You can always create immutable implementations of the data that you want to store in a Collection. If possible, this is the option that I would go with. If you go this route, you would still have to make sure that the Data elements are immutable, or have a List<ImmutableData>
instead. Using List<ImmutableData>
may not be a bad idea, but you'd probably have to have List<? extends Data>
in most method signatures.
It might look like this:
interface Data {
String getString();
MutableData toMutable();
}
class MutableData implements Data {
String getString() {...}
void setString(String s) {...}
Data toImmutable() {...}
MutableData clone() {...}
}
class ImmutableData implements Data {...}
If you still want cloning, but don't want to have to use reflection or deal with all the problems that come with the Cloneable interface, you could create your own interface that's more general for the purpose of your application.