Java ArrayList clone() Method Example

In this tutorial we will learn how to use clone() method of java.util.ArrayList class. This method returns a shallow copy of the ArrayList instance.

Signature

public Object clone()

This method returns a shallow copy of the ArrayList instance. (The elements themselves are not copied.)

Example

The following example shows the usage of java.util.Arraylist.clone() method.

import java.util.ArrayList;

public class CloneArrayListExample 
{
    public static void main(String args[])
    {
        ArrayList<String> al1 = new ArrayList<String>();
        
        //Adding elements to al1
        al1.add("one");
        al1.add("two");
        al1.add("three");
        al1.add("four");
        
        //Print the elements of al1
        System.out.println("**Elements of al1**");
        for(String val : al1)
        {
            System.out.println(val);
        }
        
        //Clone al1 to al2
        ArrayList<String> al2 = (ArrayList<String>)al1.clone();
        //Print the elements of al2
        System.out.println("**Elements of al2**");
        for(String val : al2)
        {
            System.out.println(val);
        }
    }
}

Output

**Elements of al1**
one
two
three
four
**Elements of al2**
one
two
three
four

Leave a Reply

Your email address will not be published. Required fields are marked *