Java ArrayList clone()

Here, the shallow copy means it creates copy of arraylist object. To learn more on shallow copy, visit Java Shallow Copy.

The syntax of the clone() method is:

arraylist.clone()

Here, arraylist is an object of the ArrayList class.


clone() Parameters

The clone() method does not have any parameters.


clone() Return Value

  • returns a copy of the ArrayList object

Example 1: Make a Copy of ArrayList

Output

ArrayList: [1, 3, 5]
Cloned ArrayList: [1, 3, 5]

In the above example, we have created an arraylist named number. Notice the expression,

(ArrayList<Integer>)number.clone()

Here,

  • number.clone() - returns a copy of the object number
  • (ArrayList<Integer>) - converts value returned by clone() into an arraylist of Integer type (To learn more, visit Java Typecasting)

Example 2: Print the Return Value of clone()

Output

Prime Number: [2, 3, 5]
Return value of clone(): [2, 3, 5]

In the above example, we have created an arraylist named prime. Here, we have printed the value returned by clone().

Note: The clone() method is not specific to the ArrayList class. Any class that implements the Clonable interface can use the clone() method.