Sunday, December 29, 2024
Google search engine
HomeLanguagesJavaHow to Clone a List in Java?

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:

    1. Create a list to be cloned.
    2. 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]
    
  • 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:

    1. Create a list to be cloned.
    2. Create an empty list using the ArrayList constructor.
    3. 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]
    
  • 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:

    1. Create a class
    2. Create a list of the class objects from an array using the asList method.
    3. Convert list of objects to a stream of objects using the stream() method.
    4. 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 Java
    class 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]
    
  • 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:

    1. Create a cloneable class, which has the clone method overridden.
    2. Create a list of the class objects from an array using the asList method.
    3. Create an empty list.
    4. 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 cloneable
    class 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 Java
    class 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
    ]
    
  • 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:

    1. Create a Serializable class.
    2. Create a list of the class objects from an array using the asList method.
    3. Create an empty list.
    4. 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 Serializable
    class 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 Java
    class 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:

    1. Create a class
    2. Create a list of the class objects from an array using the asList method.
    3. Use the toJson() function to create a JSON string of the original list, by passing the same as a parameter to this function.
    4. Store the returned JSON string
    5. 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 Serializable
    class 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 Java
    class 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:

    1. Create a cloneable class, which has the clone method overridden.
    2. Create a list of the class objects from an array using the asList method.
    3. Create an empty list.
    4. 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.
    5. 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 Interface
    class 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
    ]
    
RELATED ARTICLES

Most Popular

Recent Comments