How to Clone a List in Java?

Given a list in Java, the task is to clone this list.
Example:
Input: list = [“Geeks”, “for”, “Geeks”]Output: clonedList = [“Geeks”, “for”, “Geeks”]
Input: list = [“GeeksForGeeks”, “A Computer Science”, “Portal”]Output: clonedList = [“GeeksForGeeks”, “A Computer Science”, “Portal”]
In Java, there are various methods to clone a list. This article will explain some of the main methods used to achieve the same.
- Using a Copy Constructor: Using the ArrayList constructor in Java, a new list can be initialized with the elements from another collection.
Syntax:ArrayList cloned = new ArrayList(collection c); where c is the collection containing elements to be added to this list.
Approach:
- Create a list to be cloned.
- Clone the list by passing the original list as the parameter of the copy constructor of ArrayList.
The following code illustrated this example.
// Program to clone a List in Javaimportjava.util.ArrayList;importjava.util.Arrays;importjava.util.List;classExample {publicstaticvoidmain(String[] args){// Create a listList<String> original= Arrays.asList("GeeksForGeeks","A Computer Science","Portal");// Clone the listList<String> cloned_list=newArrayList<String>(original);System.out.println(cloned_list);}}Output:[GeeksForGeeks, A Computer Science, Portal]
- Using the addAll() method: The List class has a method called addAll(), which appends all the elements of one collection to the list.
Syntax:
boolean addAll(Collection c); where c is the collection containing elements to be added to this list.
Approach:
- Create a list to be cloned.
- Create an empty list using the ArrayList constructor.
- Append the original list to the empty list using the addAll() method.
The following example will illustrate this method.
// Program to clone a List in Javaimportjava.util.ArrayList;importjava.util.Arrays;importjava.util.List;classExample {publicstaticvoidmain(String[] args){// Create a listList<String> original= Arrays.asList("GeeksForGeeks","A Computer Science","Portal");List<String> cloned_list=newArrayList<String>();// Cloning a listcloned_list.addAll(original);System.out.println(cloned_list);}}Output:[GeeksForGeeks, A Computer Science, Portal]
- Using streams in Java 8 Using the Streams API introduced in JAVA 8, cloning of a list is possible. The collect() method (along with toList() method) is used to clone a list.
Approach:
- Create a class
- Create a list of the class objects from an array using the asList method.
- Convert list of objects to a stream of objects using the stream() method.
- Use the collect(Collectors.toList()) methods to collect all the stream elements list instances and returning them to the cloned_list.
The following program illustrates this concept.
importjava.util.ArrayList;importjava.util.Arrays;importjava.util.List;importjava.util.stream.Collectors;// Program to clone a List in JavaclassExample {publicstaticvoidmain(String[] args){// Create a listList<String> original= Arrays.asList("GeeksForGeeks","A Computer Science","Portal");// Clone a listList<String> cloned_list= original.stream().collect(Collectors.toList());System.out.println(cloned_list);}}Output:[GeeksForGeeks, A Computer Science, Portal]
- Using the clone() method: Clone() method of a class in Java is used to create a new instance of a class of the current object and initialized all its fields with the contents of the specified object. To clone a list, one can iterate through the original list and use the clone method to copy all the list elements and use the add method to append them to the list.
Syntax:
protected Object clone() throws CloneNotSupportedException
Approach:
- Create a cloneable class, which has the clone method overridden.
- Create a list of the class objects from an array using the asList method.
- Create an empty list.
- Loop through each element of the original list, and invoke the class object’s clone() method (which returns the class instance) and use the add() method to append it to the new list.
The following example illustrates this concept.
importjava.util.ArrayList;importjava.util.Arrays;importjava.util.List;// Class needs to be cloneableclassGfGimplementsCloneable {String username;String msg;// ConstructorGfG(String username, String msg){this.username = username;this.msg = msg;}// To print the objects in the desired format@OverridepublicString toString(){return"\nHello "+ username +" !\n"+ msg +"\n";}// Overriding the inbuilt clone class@OverrideprotectedGfG clone(){returnnewGfG(username, msg);}}// Program to clone a List in JavaclassExample {publicstaticvoidmain(String[] args){// Creating a listList<GfG> original= Arrays.asList(newGfG("Geeks","GeeksForGeeks"),newGfG("GFG","A computer science portal for geeks"));// Creating an empty listList<GfG> cloned_list=newArrayList<GfG>();// Looping through the list// and cloning each elementfor(GfG temp : original)cloned_list.add(temp.clone());System.out.println(cloned_list);}}Output:[ Hello Geeks ! GeeksForGeeks, Hello GFG ! A computer science portal for geeks ]
- Using Apache Commons Lang: The same can also be achieved by using the clone method provided by third party libraries such as Apache Commons Lang.
Syntax:public static T clone(T object) where T is the type of the object and object is the Serializable object to be cloned
Approach:
- Create a Serializable class.
- Create a list of the class objects from an array using the asList method.
- Create an empty list.
- Loop through each element of the original list, and invoke the SerializationUtils.clone() method of the serializable objects (which returns the class instance) and use the add() method to append it to the new list.
The following program illustrates this case.
importorg.apache.commons.lang3.SerializationUtils;importjava.io.Serializable;importjava.util.ArrayList;importjava.util.Arrays;importjava.util.List;// Class should be SerializableclassGfGimplementsSerializable {String username;String msg;// ConstructorGfG(String username, String msg){this.username = username;this.msg = msg;}// Overriding to print the objects// in the desired manner@OverridepublicString toString(){return"\nHello "+ username+" !\n"+ msg +"\n";}}// Program to clone a List in JavaclassExample {publicstaticvoidmain(String[] args){// Creating the listList<GfG> original= Arrays.asList(newGfG("Mukkesh","Hey there fellows!"),newGfG("McKenzie","Welcome to my page!"));// Creating an empty listList<GfG> cloned_list =newArrayList<GfG>();// Looping through the list// and cloning each element// using SerializationUtils.clonefor(GfG temp : original)cloned_list.add(SerializationUtils.clone(temp));System.out.println(cloned_list);}}Output:
[ Hello Mukkesh ! Hey there fellows!, Hello McKenzie ! Welcome to my page! ]
- Using Gson library to convert list to JSON: Using Google’s Gson library, a list can be converted to JSON. This JSON string can be converted to an object of type List and can be used to initialize the new List.
Syntax:
String gson.toJson(List a); Returns a JSON string of the List object a. List gson.fromJson(String b, Class T) Returns a list of type Class T, from the JSON string b.
Approach:
- Create a class
- Create a list of the class objects from an array using the asList method.
- Use the toJson() function to create a JSON string of the original list, by passing the same as a parameter to this function.
- Store the returned JSON string
- Create an empty list and directly initialize it to the original list’s value by using the fromJson() function and passing the stored JSON string as a parameter.
The following program illustrates this.
importcom.google.gson.Gson;importjava.util.ArrayList;importjava.util.Arrays;importjava.util.List;// Class should be SerializableclassGfGimplementsSerializable {String username;String msg;// ConstructorGfG(String username, String msg){this.username = username;this.msg = msg;}// Overriding to print the object// in the desired format@OverridepublicString toString(){return"\nHello "+ username +" !\n"+ msg +"\n";}}// Program to clone a List in JavaclassExample {publicstaticvoidmain(String[] args){// Creating a new listList<GfG> original= Arrays.asList(newGfG("Mukkesh","Hey there fellows!"),newGfG("McKenzie","Welcome to my page!"));// Creating a gson objectGson gson =newGson();// Converting the list into a json stringString jsonstring= gson.toJson(original);// Converting the json string// back into a listList<GfG> cloned_list= gson.fromJson(jsonstring, GfG);System.out.println(cloned_list);}}Output:
[ Hello Mukkesh ! Hey there fellows!, Hello McKenzie ! Welcome to my page! ]
- Using the Reflection package: The Reflection package can also be used to clone a List.
Approach:
- Create a cloneable class, which has the clone method overridden.
- Create a list of the class objects from an array using the asList method.
- Create an empty list.
- Get the clone method from the class by using the getClass().getDeclaredMethod(“clone”) method (on one element of the list), and store it as a method instance.
- Loop through each element of the list, and invoke the stored method, which will return a class instance, which can be appended to the new list.
importjava.lang.reflect.InvocationTargetException;importjava.lang.reflect.Method;importjava.util.ArrayList;importjava.util.Arrays;importjava.util.List;// GfGclass implements Cloneable InterfaceclassGfGimplementsCloneable {String username;String msg;// ConstructorGfG(String username, String msg){this.username = username;this.msg = msg;}// Overriding to print the object// in the desired format@OverridepublicString toString(){return"\nHello "+ username+"!\n"+ msg +"\n";}// Overriding the clone function@OverrideprotectedObject clone()throwsCloneNotSupportedException{returnnewGfG(username, msg);}}classListUtils {// Create a cloning functionpublicstatic<TextendsCloneable> List<T>clone(List<T> original)throwsNoSuchMethodException,InvocationTargetException,IllegalAccessException{// Boundary conditions checkedif(original ==null|| original.size() ==0) {returnnewArrayList<>();}// Get the clone method from the GfG classMethod method= original.get(0).getClass().getDeclaredMethod("clone");// Create an empty list for cloningList<T> clone =newArrayList<>();// Loop through the list and// invoke the clone method of each elementfor(T item : original) {clone.add((T)method.invoke(item));}// Return the cloned listreturnclone;}publicstaticvoidmain(String[] args){// Creating a listList<GfG> original= Arrays.asList(newGfG("Geeks","GeeksForGeeks"),newGfG("GFG","A computer science portal for geeks"));// Create an empty list for cloningList<GfG> cloned_list =null;// Use try and catch for exception handlingtry{cloned_list = clone(original);}catch(NoSuchMethodException e) {e.printStackTrace();}catch(InvocationTargetException e) {e.printStackTrace();}catch(IllegalAccessException e) {e.printStackTrace();}// Print the cloned listSystem.out.println(cloned_list);}}Output:[ Hello Geeks! GeeksForGeeks, Hello GFG! A computer science portal for geeks ]



