How to Clone a List in Java?

03 Apr, 2019
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 Java  import java.util.ArrayList;import java.util.Arrays;import java.util.List;  class Example {    public static void main(String[] args)    {        // Create a list        List<String> original            = Arrays.asList(                "GeeksForGeeks",                "A Computer Science",                "Portal");          // Clone the list        List<String> cloned_list            = new ArrayList<String>(original);          System.out.println(cloned_list);    }}Output:[GeeksForGeeks, A Computer Science, Portal]

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.
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 Java  import java.util.ArrayList;import java.util.Arrays;import java.util.List;  class Example {    public static void main(String[] args)    {        // Create a list        List<String> original            = Arrays.asList(                "GeeksForGeeks",                "A Computer Science",                "Portal");          // Clone the list        List<String> cloned_list            = new ArrayList<String>(original);          System.out.println(cloned_list);    }}
[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 Java  import java.util.ArrayList;import java.util.Arrays;import java.util.List;  class Example {    public static void main(String[] args)    {        // Create a list        List<String> original            = Arrays.asList(                "GeeksForGeeks",                "A Computer Science",                "Portal");          List<String> cloned_list            = new ArrayList<String>();          // Cloning a list        cloned_list.addAll(original);          System.out.println(cloned_list);    }}Output:[GeeksForGeeks, A Computer Science, Portal]

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.
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 Java  import java.util.ArrayList;import java.util.Arrays;import java.util.List;  class Example {    public static void main(String[] args)    {        // Create a list        List<String> original            = Arrays.asList(                "GeeksForGeeks",                "A Computer Science",                "Portal");          List<String> cloned_list            = new ArrayList<String>();          // Cloning a list        cloned_list.addAll(original);          System.out.println(cloned_list);    }}
[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 classCreate 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.import java.util.ArrayList;import java.util.Arrays;import java.util.List;import java.util.stream.Collectors;  // Program to clone a List in Javaclass Example {    public static void main(String[] args)    {        // Create a list        List<String> original            = Arrays.asList(                "GeeksForGeeks",                "A Computer Science",                "Portal");          // Clone a list        List<String> cloned_list            = original.stream()                  .collect(Collectors.toList());          System.out.println(cloned_list);    }}Output:[GeeksForGeeks, A Computer Science, Portal]

Approach:
Create a classCreate 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.
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.
import java.util.ArrayList;import java.util.Arrays;import java.util.List;import java.util.stream.Collectors;  // Program to clone a List in Javaclass Example {    public static void main(String[] args)    {        // Create a list        List<String> original            = Arrays.asList(                "GeeksForGeeks",                "A Computer Science",                "Portal");          // Clone a list        List<String> cloned_list            = original.stream()                  .collect(Collectors.toList());          System.out.println(cloned_list);    }}
[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.import java.util.ArrayList;import java.util.Arrays;import java.util.List;  // Class needs to be cloneableclass GfG implements Cloneable {      String username;    String msg;      // Constructor    GfG(String username, String msg)    {        this.username = username;        this.msg = msg;    }      // To print the objects in the desired format    @Override    public String toString()    {        return "\nHello " + username + " !\n" + msg + "\n";    }      // Overriding the inbuilt clone class    @Override    protected GfG clone()    {        return new GfG(username, msg);    }}  // Program to clone a List in Javaclass Example {    public static void main(String[] args)    {        // Creating a list        List<GfG> original            = Arrays.asList(                new GfG("Geeks",                        "GeeksForGeeks"),                new GfG("GFG",                        "A computer science portal for geeks"));          // Creating an empty list        List<GfG> cloned_list            = new ArrayList<GfG>();          // Looping through the list        // and cloning each element        for (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
]

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.
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.
import java.util.ArrayList;import java.util.Arrays;import java.util.List;  // Class needs to be cloneableclass GfG implements Cloneable {      String username;    String msg;      // Constructor    GfG(String username, String msg)    {        this.username = username;        this.msg = msg;    }      // To print the objects in the desired format    @Override    public String toString()    {        return "\nHello " + username + " !\n" + msg + "\n";    }      // Overriding the inbuilt clone class    @Override    protected GfG clone()    {        return new GfG(username, msg);    }}  // Program to clone a List in Javaclass Example {    public static void main(String[] args)    {        // Creating a list        List<GfG> original            = Arrays.asList(                new GfG("Geeks",                        "GeeksForGeeks"),                new GfG("GFG",                        "A computer science portal for geeks"));          // Creating an empty list        List<GfG> cloned_list            = new ArrayList<GfG>();          // Looping through the list        // and cloning each element        for (GfG temp : original)            cloned_list.add(temp.clone());        System.out.println(cloned_list);    }}
[
Hello Geeks !
GeeksForGeeks, 
Hello GFG !
A computer science portal for geeks
]

Using Apache Commons Lang: The same can also be aschieved 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.import org.apache.commons.lang3.SerializationUtils;import java.io.Serializable;import java.util.ArrayList;import java.util.Arrays;import java.util.List;  // Class should be Serializableclass GfG implements Serializable {    String username;    String msg;      // Constructor    GfG(String username, String msg)    {        this.username = username;        this.msg = msg;    }      // Overriding to print the objects    // in the desired manner    @Override    public String toString()    {        return "\nHello " + username            + " !\n" + msg + "\n";    }}  // Program to clone a List in Javaclass Example {    public static void main(String[] args)    {        // Creating the list        List<GfG> original            = Arrays.asList(                new GfG("Mukkesh",                        "Hey there fellows!"),                new GfG("McKenzie",                        "Welcome to my page!"));          // Creating an empty list        List<GfG> cloned_list = new ArrayList<GfG>();          // Looping through the list        // and cloning each element        // using SerializationUtils.clone        for (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!
]

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.
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.
import org.apache.commons.lang3.SerializationUtils;import java.io.Serializable;import java.util.ArrayList;import java.util.Arrays;import java.util.List;  // Class should be Serializableclass GfG implements Serializable {    String username;    String msg;      // Constructor    GfG(String username, String msg)    {        this.username = username;        this.msg = msg;    }      // Overriding to print the objects    // in the desired manner    @Override    public String toString()    {        return "\nHello " + username            + " !\n" + msg + "\n";    }}  // Program to clone a List in Javaclass Example {    public static void main(String[] args)    {        // Creating the list        List<GfG> original            = Arrays.asList(                new GfG("Mukkesh",                        "Hey there fellows!"),                new GfG("McKenzie",                        "Welcome to my page!"));          // Creating an empty list        List<GfG> cloned_list = new ArrayList<GfG>();          // Looping through the list        // and cloning each element        // using SerializationUtils.clone        for (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 classCreate 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 stringCreate 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.import com.google.gson.Gson;import java.util.ArrayList;import java.util.Arrays;import java.util.List;  // Class should be Serializableclass GfG implements Serializable {    String username;    String msg;      // Constructor    GfG(String username, String msg)    {        this.username = username;        this.msg = msg;    }      // Overriding to print the object    // in the desired format    @Override    public String toString()    {        return "\nHello " + username + " !\n" + msg + "\n";    }}  // Program to clone a List in Javaclass Example {    public static void main(String[] args)    {        // Creating a new list        List<GfG> original            = Arrays.asList(new GfG("Mukkesh",                                    "Hey there fellows!"),                            new GfG("McKenzie",                                    "Welcome to my page!"));        // Creating a gson object        Gson gson = new Gson();          // Converting the list into a json string        String jsonstring            = gson.toJson(original);          // Converting the json string        // back into a list        List<GfG> cloned_list            = gson.fromJson(jsonstring, GfG);          System.out.println(cloned_list);    }}Output:[
Hello Mukkesh !
Hey there fellows!, 
Hello McKenzie !
Welcome to my page!
]

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 classCreate 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 stringCreate 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.
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.
import com.google.gson.Gson;import java.util.ArrayList;import java.util.Arrays;import java.util.List;  // Class should be Serializableclass GfG implements Serializable {    String username;    String msg;      // Constructor    GfG(String username, String msg)    {        this.username = username;        this.msg = msg;    }      // Overriding to print the object    // in the desired format    @Override    public String toString()    {        return "\nHello " + username + " !\n" + msg + "\n";    }}  // Program to clone a List in Javaclass Example {    public static void main(String[] args)    {        // Creating a new list        List<GfG> original            = Arrays.asList(new GfG("Mukkesh",                                    "Hey there fellows!"),                            new GfG("McKenzie",                                    "Welcome to my page!"));        // Creating a gson object        Gson gson = new Gson();          // Converting the list into a json string        String jsonstring            = gson.toJson(original);          // Converting the json string        // back into a list        List<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.import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.util.ArrayList;import java.util.Arrays;import java.util.List;  // GfGclass implements Cloneable Interfaceclass GfG implements Cloneable {    String username;    String msg;      // Constructor    GfG(String username, String msg)    {        this.username = username;        this.msg = msg;    }      // Overriding to print the object    // in the desired format    @Override    public String toString()    {        return "\nHello " + username            + "!\n" + msg + "\n";    }      // Overriding the clone function    @Override    protected Object clone()        throws CloneNotSupportedException    {        return new GfG(username, msg);    }}  class ListUtils {    // Create a cloning function    public static <T extends Cloneable> List<T>    clone(List<T> original)        throws NoSuchMethodException,               InvocationTargetException,               IllegalAccessException    {          // Boundary conditions checked        if (original == null            || original.size() == 0) {            return new ArrayList<>();        }          // Get the clone method from the GfG class        Method method            = original.get(0)                  .getClass()                  .getDeclaredMethod("clone");          // Create an empty list for cloning        List<T> clone = new ArrayList<>();          // Loop through the list and        // invoke the clone method of each element        for (T item : original) {            clone.add((T)method.invoke(item));        }          // Return the cloned list        return clone;    }      public static void main(String[] args)    {        // Creating a list        List<GfG> original            = Arrays.asList(                new GfG("Geeks",                        "GeeksForGeeks"),                new GfG("GFG",                        "A computer science portal for geeks"));          // Create an empty list for cloning        List<GfG> cloned_list = null;          // Use try and catch for exception handling        try {            cloned_list = clone(original);        }        catch (NoSuchMethodException e) {            e.printStackTrace();        }        catch (InvocationTargetException e) {            e.printStackTrace();        }        catch (IllegalAccessException e) {            e.printStackTrace();        }          // Print the cloned list        System.out.println(cloned_list);    }}Output:[
Hello Geeks!
GeeksForGeeks, 
Hello GFG!
A computer science portal for geeks
]

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.
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.
import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.util.ArrayList;import java.util.Arrays;import java.util.List;  // GfGclass implements Cloneable Interfaceclass GfG implements Cloneable {    String username;    String msg;      // Constructor    GfG(String username, String msg)    {        this.username = username;        this.msg = msg;    }      // Overriding to print the object    // in the desired format    @Override    public String toString()    {        return "\nHello " + username            + "!\n" + msg + "\n";    }      // Overriding the clone function    @Override    protected Object clone()        throws CloneNotSupportedException    {        return new GfG(username, msg);    }}  class ListUtils {    // Create a cloning function    public static <T extends Cloneable> List<T>    clone(List<T> original)        throws NoSuchMethodException,               InvocationTargetException,               IllegalAccessException    {          // Boundary conditions checked        if (original == null            || original.size() == 0) {            return new ArrayList<>();        }          // Get the clone method from the GfG class        Method method            = original.get(0)                  .getClass()                  .getDeclaredMethod("clone");          // Create an empty list for cloning        List<T> clone = new ArrayList<>();          // Loop through the list and        // invoke the clone method of each element        for (T item : original) {            clone.add((T)method.invoke(item));        }          // Return the cloned list        return clone;    }      public static void main(String[] args)    {        // Creating a list        List<GfG> original            = Arrays.asList(                new GfG("Geeks",                        "GeeksForGeeks"),                new GfG("GFG",                        "A computer science portal for geeks"));          // Create an empty list for cloning        List<GfG> cloned_list = null;          // Use try and catch for exception handling        try {            cloned_list = clone(original);        }        catch (NoSuchMethodException e) {            e.printStackTrace();        }        catch (InvocationTargetException e) {            e.printStackTrace();        }        catch (IllegalAccessException e) {            e.printStackTrace();        }          // Print the cloned list        System.out.println(cloned_list);    }}
[
Hello Geeks!
GeeksForGeeks, 
Hello GFG!
A computer science portal for geeks
]

java-list
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.