ArrayList clone() method in java

Let’s learn ArrayList clone() method in java.

ArrayList clone() method in java

clone() method of ArrayList class returns a shallow copy of this ArrayList instance.

Also read – ArrayList in java

Syntax:

ArrayList.clone()

Now let’s see example on clone() method.

import java.util.ArrayList;
public class ArrayListCloneMethodExample
{
   public static void main(String[] args)
   {
      ArrayList<String> al = new ArrayList<String>();
      al.add("violet");
      al.add("indigo");
      al.add("blue");
      al.add("green");
      al.add("yellow");
      System.out.println("ArrayList before using clone() method: " + al);
      // create another ArrayList and copy
      ArrayList<String> arrClone = new ArrayList<String>();
      arrClone = (ArrayList)al.clone();
      System.out.println("ArrayList after using clone() method: " + arrClone);
   }
}


Output:

ArrayList before using clone() method: [violet, indigo, blue, green, yellow]
ArrayList after using clone() method: [violet, indigo, blue, green, yellow]


Let’s see another example.

import java.util.ArrayList;
public class ArrayListCloneMethodExample
{
   public static void main(String[] args)
   {
      ArrayList<Integer> al = new ArrayList<Integer>();
      al.add(20);
      al.add(40);
      al.add(60);
      al.add(80);
      al.add(100);
      System.out.println("ArrayList before using clone() method: " + al);
      // create another ArrayList and copy
      ArrayList<Integer> arrClone = new ArrayList<Integer>();
      arrClone = (ArrayList)al.clone();
      System.out.println("ArrayList after using clone() method: " + arrClone);
   }
}


Output:

ArrayList before using clone() method: [20, 40, 60, 80, 100]
ArrayList after using clone() method: [20, 40, 60, 80, 100]