Java Utility Library

Java ArrayList - clone() Method



The java.util.ArrayList.clone() method returns a shallow copy of the given ArrayList.

Syntax

public Object clone()

Parameters

No parameter is required.

Return Value

Returns a shallow copy of the given ArrayList instance.

Exception

NA

Example:

In the example below, the java.util.ArrayList.clone() method is used to create a shallow copy of the ArrayList called MyList.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating an ArrayList
    ArrayList<Integer> MyList = new ArrayList<Integer>();

    //populating ArrayList
    MyList.add(10);
    MyList.add(20);
    MyList.add(30);
    
    ArrayList NewList = new ArrayList();
    NewList = (ArrayList) MyList.clone();

    //printing ArrayList
    System.out.println("NewList contains: " + NewList);
  }
}

The output of the above code will be:

NewList contains: [10, 20, 30]

❮ Java.util - ArrayList