How do I clone a generic List in Java?

Question!

I have an ArrayList<String> that I'd like to return a copy of. ArrayList has a clone method has the following signature:

public Object clone()

After I call this method, how do I cast the returned Object back to ArrayList<String>?



Answers

To clone a generic interface like java.util.List you will just need to cast it. here you are an example:

List list = new ArrayList();
List list2 = ((List) ( (ArrayList) list).clone());

It is a bit tricky, but it works, if you are limited to return a List interface, so anyone after you can implement your list whenever he wants.

I know this answer is close to the final answer, but my answer answers how to do all of that while you are working with List -the generic parent- not ArrayList



If you want this in order to be able to return the List in a getter it would be better to do:

ImmutableList.copyOf(list);


With Java 8 it can be cloned with a stream.

import static java.util.stream.Collectors.toList;

...

List<AnObject> clone = myList.stream().collect(toList());


This video can help you solving your question :)
By: admin