Clone a List in Java

In this post, we will see how to clone a List in Java. We need to construct a list containing the elements of the specified list, 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. 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.

 

Download   Run Code

Output:

[{John, 25}, {Kim, 20}]

 

2. Using addAll(Collection<? extends E> c)

List interface has addAll() method that appends all of the elements in the specified collection to the end of a list. We can use the same to copy elements from the original list to an empty list.

 

Download   Run Code

 

3. Java 8

We can also use Streams in Java 8 to clone a list as shown below:

 

Download   Run Code

 

4. Object clone() method

Java Object class provides 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 cloned list. We can also use Java 8 Stream to do the same.

 

Download   Run Code

Output:

[{John, 25}, {Kim, 20}]

 

5. Apache Commons Lang

There are many third party libraries that provides convenient classes for 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:

 

Download

Output:

[{John, 25}, {Kim, 20}]

 

6. 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 new List Object and return it.

 

Download

Output:

[{John, 25}, {Kim, 20}]

 

7. Reflection

We can also use Reflection to clone a List as shown below.

 

Download   Run Code

Output:

[{John, 25}, {Kim, 20}]

 
Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
newest oldest most voted
Notify of
Naveen
Guest

Thanks!