Clone an ArrayList in Java


An ArrayList can be cloned using the java.util.ArrayList.clone() method. This method does not take any parameters but returns a shallow copy the specified ArrayList instance. This means that the new ArrayList created using the ArrayList.clone() method refers to the same elements as the original ArrayList but it does not duplicate the elements.

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.util.ArrayList;
import java.util.List;
public class Demo {
   public static void main(String[] args) {
      List aList1 = new ArrayList();
      aList1.add("Apple");
      aList1.add("Mango");
      aList1.add("Guava");
      aList1.add("Orange");
      aList1.add("Peach");
      List aList2 = ((List) ((ArrayList) aList1).clone());
      System.out.println("Elements in aList1: " + aList1);
      System.out.println("Elements in aList2: " + aList2);
   }
}

Output

Elements in aList1: [Apple, Mango, Guava, Orange, Peach]
Elements in aList2: [Apple, Mango, Guava, Orange, Peach]

Now let us understand the above program.

The ArrayList aList1 is created. Then ArrayList.add() is used to add the elements to this ArrayList. The aList1 is cloned using the java.util.ArrayList.clone() method into aList2. Then the elements of aList1 and aList2 are displayed. A code snippet which demonstrates this is as follows −

List aList1 = new ArrayList();
aList1.add("Apple");
aList1.add("Mango");
aList1.add("Guava");
aList1.add("Orange");
aList1.add("Peach");
List aList2 = ((List) ((ArrayList) aList1).clone());
System.out.println("Elements in aList1: " + aList1);
System.out.println("Elements in aList2: " + aList2);

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019

335 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements