Java list which clones elements when added

Sambo :

Is there a Java class which implements the List interface and which clones elements when they are added to the list? The goal of this would be to preserve encapsulation of this list as an object.

Of course, it would be easy to write one myself by taking, say, ArrayList and wrappering it in another class, then calling the clone method when implementing the add and get methods. But, I figured I'd ask if such a class was already provided by Java and potentially save myself some tedious coding.

retodaredevil :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=114951&siteId=1