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:
Java
import java.util.ArrayList;
public class GFG {
public static void main(String a[])
{
ArrayList<String> ArrList1
= new ArrayList<String>();
ArrList1.add( "Mukul" );
ArrList1.add( "Rahul" );
ArrList1.add( "Suraj" );
ArrList1.add( "Mayank" );
System.out.println( "Original ArrayList = "
+ ArrList1);
ArrayList ArrList2
= (ArrayList)ArrList1.clone();
System.out.println( "Clone ArrayList2 = "
+ ArrList2);
}
}
|
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
import java.io.*;
import java.util.*;
public class ArrayListDemo {
public static void main(String args[])
{
ArrayList<Integer> list = new ArrayList<Integer>();
list.add( 16 );
list.add( 32 );
list.add( 48 );
System.out.println( "First ArrayList: " + list);
ArrayList<Integer> sec_list
= (ArrayList<Integer>)list.clone();
sec_list.add( 64 );
System.out.println( "First ArrayList: " + 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)
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
19 Jul, 2022
Like Article
Save Article