Clone a List in Java
This post will discuss how to clone a list in Java. We need to construct a list containing the specified list elements in the same order as the original list.
Assume there are no mutable objects in the list, i.e., the code can perform a shallow copy.
1. Using Copy Constructor
We can use a copy constructor to clone a list, which is a special constructor for creating a new object as a copy of an existing object.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
import java.util.ArrayList; import java.util.Arrays; import java.util.List; class Person { String name; Integer age; Person(String name, Integer age) { this.name = name; this.age = age; } @Override public String toString() { return "{" + name + ", " + age + "}"; } } // Program to clone a list in Java class Main { public static<T> List<T> clone(List<T> original) { List<T> copy = new ArrayList<>(original); return copy; } public static void main(String[] args) { List<Person> original = Arrays.asList(new Person("John", 25), new Person("Kim", 20)); List<Person> copy = clone(original); System.out.println(copy); } } |
Output:
[{John, 25}, {Kim, 20}]
2. Using addAll(Collection<? extends E> c) method
List interface has the addAll() method that appends all the elements in the specified collection at the end of a list. We can use the same to copy elements from the original list to an empty list.
|
1 2 3 4 5 |
public static<T> List<T> clone(List<T> original) { List<T> copy = new ArrayList<>(); copy.addAll(original); return copy; } |
3. Using Java 8
We can also use streams in Java 8 and above to clone a list, as shown below:
|
1 2 3 4 5 |
public static<T> List<T> clone(List<T> original) { List<T> copy = original.stream() .collect(Collectors.toList()); return copy; } |
4. Using Object.clone() method
Java Object class provides the clone() method, which can be overridden by implementing the Cloneable interface. The idea is to iterate through the list, clone each item, and add it to the cloned list. We can also use Java 8 Stream to do the same.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
import java.util.ArrayList; import java.util.Arrays; import java.util.List; // Note that the `Person` class implements `Cloneable` interface class Person implements Cloneable { String name; Integer age; Person(String name, Integer age) { this.name = name; this.age = age; } @Override public String toString() { return "{" + name + ", " + age + "}"; } @Override protected Person clone() { return new Person(name, age); } } // Program to clone a list in Java class Main { public static void main(String[] args) { List<Person> original = Arrays.asList(new Person("John", 25), new Person("Kim", 20)); List<Person> copy = new ArrayList<>(original.size()); for (Person person: original) { copy.add(person.clone()); } /* // in Java 8 and above List<Person> copy = original.stream() .map(Person::clone) .collect(Collectors.toList()); */ System.out.println(copy); } } |
Output:
[{John, 25}, {Kim, 20}]
5. Using Apache Commons Lang
Several third-party libraries provide convenient classes for the Serialization and Deserialization of objects. One such class is SerializationUtils provided by Apache Commons Lang which has serialize() and deserialize() methods to serialize/deserialize an object. The serialized object holds no reference to the original object on deserialization.
SerializationUtils also provides clone() method, which is shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
import org.apache.commons.lang3.SerializationUtils; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.List; // Note that the `Person` class implements `Serializable` interface class Person implements Serializable { String name; Integer age; Person(String name, Integer age) { this.name = name; this.age = age; } @Override public String toString() { return "{" + name + ", " + age + "}"; } } // Program to clone a list in Java class Main { public static <T extends Serializable> List<T> clone(List<T> original) { List<T> copy = new ArrayList<>(); for (T item: original) { copy.add(SerializationUtils.clone(item)); } return copy; } public static void main(String[] args) { List<Person> original = Arrays.asList(new Person("John", 25), new Person("Kim", 20)); List<Person> copy = clone(original); System.out.println(copy); } } |
Output:
[{John, 25}, {Kim, 20}]
6. Using JSON
We can also convert the list to a JSON string using Google’s Gson library. Then we can convert the JSON string back to a new list object and return it.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
import com.google.gson.Gson; import java.util.Arrays; import java.util.List; class Person { String name; Integer age; Person(String name, Integer age) { this.name = name; this.age = age; } @Override public String toString() { return "{" + name + ", " + age + "}"; } } // Program to clone a list in Java class Main { public static <T> List<T> clone(List<T> original) { Gson gson = new Gson(); // Convert the list to JSON string String jsonString = gson.toJson(original); // Convert the JSON string back to a new list object and return it List<T> copy = gson.fromJson(jsonString, List.class); return copy; } public static void main(String[] args) { List<Person> original = Arrays.asList(new Person("John", 25), new Person("Kim", 20)); List<Person> copy = clone(original); System.out.println(copy); } } |
Output:
[{John, 25}, {Kim, 20}]
7. Using Reflection
We can also use Reflection to clone a list, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.List; // Note that the `Person` class implements `Cloneable` interface class Person implements Cloneable { String name; Integer age; Person(String name, Integer age) { this.name = name; this.age = age; } @Override public String toString() { return "{" + name + ", " + age + "}"; } @Override protected Object clone() throws CloneNotSupportedException { return new Person(name, age); } } // Program to clone a list in Java class Main { public static <T extends Cloneable> List<T> clone(List<T> original) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { if (original == null || original.size() == 0) { return new ArrayList<>(); } Method method = original.get(0).getClass().getDeclaredMethod("clone"); List<T> clone = new ArrayList<>(); for (T item: original) { clone.add((T) method.invoke(item)); } return clone; } public static void main(String[] args) { List<Person> original = Arrays.asList(new Person("John", 25), new Person("Kim", 20)); List<Person> copy = null; try { copy = clone(original); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } System.out.println(copy); } } |
Output:
[{John, 25}, {Kim, 20}]
That’s all about cloning a List in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)