Skip to content
Related Articles

Related Articles

How to clone an ArrayList to another ArrayList in Java?

View Discussion
Improve Article
Save Article
Like Article
  • Difficulty Level : Hard
  • Last Updated : 08 Dec, 2020

The clone() method of the ArrayList class is used to clone an ArrayList to another ArrayList in Java as it returns a shallow copy of its caller ArrayList. 


public Object clone();

Return Value: This function returns a copy of the instance of Object.

Below program illustrate the Java.util.ArrayList.clone() method:



// Java program to clone an ArrayList to another ArrayList
import java.util.ArrayList;
public class GFG {
    public static void main(String a[])
        // create ArrayList
        ArrayList<String> ArrList1
            = new ArrayList<String>();
        // Insert elements in ArrayList
        // print ArrayList1
        System.out.println("Original ArrayList = "
                           + ArrList1);
        // clone ArrayList
        ArrayList ArrList2
            = (ArrayList)ArrList1.clone();
        // print ArrayList2
        System.out.println("Clone ArrayList2 = "
                           + ArrList2);


Original ArrayList = [Mukul, Rahul, Suraj, Mayank]
Clone ArrayList2 = [Mukul, Rahul, Suraj, Mayank]

Example 2:


// Java code to illustrate clone() method
import java.util.*;
public class ArrayListDemo {
    public static void main(String args[])
        // Creating an empty ArrayList
        ArrayList<Integer> list = new ArrayList<Integer>();
        // Use add() method
        // to add elements in the list
        // Displaying the list
        System.out.println("First ArrayList: " + list);
        // Creating another linked list and copying
        // creates a shallow copy
        ArrayList<Integer> sec_list
            = (ArrayList<Integer>)list.clone();
        // Displaying the list
        System.out.println("First ArrayList: " + list);
        // Displaying the other linked list
        System.out.println("Second ArrayList is: "
                           + sec_list);


First ArrayList: [16, 32, 48]
First ArrayList: [16, 32, 48]
Second ArrayList is: [16, 32, 48, 64]

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!