[java] 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>?

This question is related to java generics arraylist clone

The answer is


This should also work:

ArrayList<String> orig = new ArrayList<String>();
ArrayList<String> copy = (ArrayList<String>) orig.clone()

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.


I am not a java professional, but I have the same problem and I tried to solve by this method. (It suppose that T has a copy constructor).

 public static <T extends Object> List<T> clone(List<T> list) {
      try {
           List<T> c = list.getClass().newInstance();
           for(T t: list) {
             T copy = (T) t.getClass().getDeclaredConstructor(t.getclass()).newInstance(t);
             c.add(copy);
           }
           return c;
      } catch(Exception e) {
           throw new RuntimeException("List cloning unsupported",e);
      }
}

I find using addAll works fine.

ArrayList<String> copy = new ArrayList<String>();
copy.addAll(original);

parentheses are used rather than the generics syntax


List<String> shallowClonedList = new ArrayList<>(listOfStrings);

Keep in mind that this is only a shallow not a deep copy, ie. you get a new list, but the entries are the same. This is no problem for simply strings. Get's more tricky when the list entries are objects themself.


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.


ArrayList first = new ArrayList ();
ArrayList copy = (ArrayList) first.clone ();

Be very careful when cloning ArrayLists. Cloning in java is shallow. This means that it will only clone the Arraylist itself and not its members. So if you have an ArrayList X1 and clone it into X2 any change in X2 will also manifest in X1 and vice-versa. When you clone you will only generate a new ArrayList with pointers to the same elements in the original.


This is the code I use for that:

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

Hope is usefull for you


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());

I think this should do the trick using the Collections API:

Note: the copy method runs in linear time.

//assume oldList exists and has data in it.
List<String> newList = new ArrayList<String>();
Collections.copy(newList, oldList);

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to generics

Instantiating a generic type Are these methods thread safe? The given key was not present in the dictionary. Which key? Using Java generics for JPA findAll() query with WHERE clause Using Spring RestTemplate in generic method with generic parameter How to create a generic array? Create a List of primitive int? How to have Java method return generic list of any type? Create a new object from type parameter in generic class What is the "proper" way to cast Hibernate Query.list() to List<Type>?

Examples related to arraylist

Adding null values to arraylist How to iterate through an ArrayList of Objects of ArrayList of Objects? Dynamically adding elements to ArrayList in Groovy How to replace existing value of ArrayList element in Java How to remove the last element added into the List? How to append elements at the end of ArrayList in Java? Removing Duplicate Values from ArrayList How to declare an ArrayList with values? In Java, can you modify a List while iterating through it? Load arrayList data into JTable

Examples related to clone

git clone error: RPC failed; curl 56 OpenSSL SSL_read: SSL_ERROR_SYSCALL, errno 10054 git: fatal: I don't handle protocol '??http' How to make a copy of an object in C# How create a new deep copy (clone) of a List<T>? "fatal: Not a git repository (or any of the parent directories)" from git status How to copy java.util.list Collection How to jQuery clone() and change id? Copying a HashMap in Java jquery clone div and append it after specific div jQuery Clone table row