Open In App

How to clone an ArrayList to another ArrayList in Java?

Last Updated : 19 Jul, 2022
Comments
Improve
Suggest changes
17 Likes
Like
Report

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. 

Syntax:

public Object clone();

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

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

Example:


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

Time complexity: O(N) where N is the size of ArrayList

Auxiliary Space: O(N)

Example 2:

// Java code to illustrate clone() method

import java.io.*;
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
        list.add(16);
        list.add(32);
        list.add(48);

        // 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();

        sec_list.add(64);

        // Displaying the list
        System.out.println("First ArrayList: " + list);
        
        // Displaying the other linked list
        System.out.println("Second ArrayList is: "
                           + sec_list);
    }
}

Output

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

Time complexity: O(N) where N is the size of ArrayList

Auxiliary Space: O(N)


Next Article

Similar Reads