I have an ArrayList
that I\'d like to return a copy of. ArrayList
has a clone method which has the following signature:
With Java 8 it can be cloned with a stream.
import static java.util.stream.Collectors.toList;
...
List<AnObject> clone = myList.stream().collect(toList());
ArrayList newArrayList = (ArrayList) oldArrayList.clone();
This is the code I use for that:
ArrayList copy = new ArrayList (original.size());
Collections.copy(copy, original);
Hope is usefull for you
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.
This should also work:
ArrayList<String> orig = new ArrayList<String>();
ArrayList<String> copy = (ArrayList<String>) orig.clone()
ArrayList first = new ArrayList ();
ArrayList copy = (ArrayList) first.clone ();