Deep copy of List<> without knowing specific list type
-
I have some DTOs that are written to be immutable.
private List foo;
... [omitted for brevity]
public List getFoo() {
List bar = new ArrayList(foo.size());for (Transformation listEntry : foo) { bar.add(Transformation.of(listEntry)); } return bar;
}
This works for my current application as I happen to know that the Lists are all ArrayLists. What if I didn't know that? Is there a way to deep copy the contents of an arbitrary implementation of List without knowing what type that underlying List is?
-
I have some DTOs that are written to be immutable.
private List foo;
... [omitted for brevity]
public List getFoo() {
List bar = new ArrayList(foo.size());for (Transformation listEntry : foo) { bar.add(Transformation.of(listEntry)); } return bar;
}
This works for my current application as I happen to know that the Lists are all ArrayLists. What if I didn't know that? Is there a way to deep copy the contents of an arbitrary implementation of List without knowing what type that underlying List is?
As long as ListType is clonable, you can do it as following
bar.add(listEntry.clone());