Copy/clone an ArrayList to another in Java

In this tutorial, we'll look at how to copy all the items from one ArrayList into another ArrayList. We must use the method clone() of the parent class Object to achieve our goal.

Object clone(): This method returns a copy of the ArrayList.

Cloning does not mean that both the original and cloned lists point to the same memory box. This is done just with List b = a; . If you change an item in the first list, it will also be changed in the second list.

Cloning creates a new instance that maintains the same items. This means that you have two different lists, but their contents are the same. If you change an element in the first list, it will not change in the second list.

In this example, we have an ArrayList of type String and we are cloning it using the method  clone().  The interesting point here is when to add and remove items to the original list after the clone.

import java.util.ArrayList; 

public class ArrayList_clone {

public static void main(String[] args) {
ArrayList< String> al = new ArrayList< String> ();

//Add Items to ArrayList
al.add("Pen");
al.add("Kit");
al.add("Pencil");
al.add("Calculator");
System.out.println("ArrayList: "+al);

ArrayList< String> al2 = (ArrayList< String>) al.clone();
System.out.println("Cloned ArrayList: "+ al2);

//add and remove items from the original list
al.add("Notebook");
al.remove("Pencil");

//Show both lists after adding and deleting
System.out.println("Original ArrayList: "+al);
System.out.println("Cloned ArrayList: "+al2);
}
}
Runtime:

ArrayList: [Pen, Kit, Pencil, Calculator]
Cloned ArrayList: [Pen, Kit, Pencil, Calculator]
ArrayList Original: [Pen, Kit, Calculator, Notebook]
Cloned ArrayList: [Pen, Kit, Pencil, Calculator]
However, you should consider not using the clone() method. It works very well with collections, but generally, it's better to use the builder new ArrayList.