How to Clone an ArrayList to another

In this tutorial we will learn how to clone one ArrayList to another. We will be using clone() method of ArrayList class.

Cloning an ArrayList to another

Below are the steps we will be performing

  • Create a new arraylist arraylist al1.
  • Add elements to al1  add() method.
  • Create a new ArrayList al2, use clone() method to clone al1 to al2.
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 *