How do I clone a generic List in Java?

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

public Object clone()

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


Solution 1:

Why would you want to clone? Creating a new list usually makes more sense.

List<String> strs;
...
List<String> newStrs = new ArrayList<>(strs);

Job done.

Solution 2:

ArrayList newArrayList = (ArrayList) oldArrayList.clone();

Solution 3:

This is the code I use for that:

ArrayList copy = new ArrayList (original.size());
Collections.copy(copy, original);

Hope is usefull for you

Solution 4:

Be advised that Object.clone() has some major problems, and its use is discouraged in most cases. Please see Item 11, from "Effective Java" by Joshua Bloch for a complete answer. I believe you can safely use Object.clone() on primitive type arrays, but apart from that you need to be judicious about properly using and overriding clone. You are probably better off defining a copy constructor or a static factory method that explicitly clones the object according to your semantics.

Solution 5:

With Java 8 it can be cloned with a stream.

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

...

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