How do I clone a generic List in Java?

Bill the Lizard picture Bill the Lizard · Sep 10, 2008 · Viewed 253k times · Source

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>?

Answer

Tom Hawtin - tackline picture Tom Hawtin - tackline · Sep 11, 2008

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.