English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List

Java Queue (queue)

Java Map collection

Java Set collection

Java Input Output (I/O)

Java Reader/Writer

Java other topics

Java ArrayList clone() method usage and example

Java ArrayList Methods

The Java ArrayList clone() method generates a shallow copy of ArrayList.

Here, shallow copy means it will create a copy of the arraylist object.

The syntax of the clone() method is:

arraylist.clone()

clone() parameters

The clone() method has no parameters.

clone() return value

  • Return a copy of the ArrayList object

Example1: Copy ArrayList

import java.util.ArrayList;
class Main {
    public static void main(String[] args) {
        //Create an ArrayList
        ArrayList<Integer> number = new ArrayList<>();
        number.add(1);
        number.add(3);
        number.add(5);
        System.out.println("ArrayList: ", + number);
        // Create a copy of number
        ArrayList<Integer> cloneNumber = (ArrayList<Integer>)number.clone();
        System.out.println("ArrayList copy: ", + cloneNumber);
    }
}

Output Result

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

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

(ArrayList<Integer>)number.clone()

Here,

  • number.clone() - Return a copy of the object number

  • (ArrayList<Integer>) -  Convert the clone() return value to an Integer type arraylist (For more information, please visitJava Type Conversion)

Example2: Print the return value of clone()

import java.util.ArrayList;
class Main {
    public static void main(String[] args) {
        //Create an ArrayList
        ArrayList<Integer> prime = new ArrayList<>();
        prime.add(2);
        prime.add(3);
        prime.add(5);
        System.out.println("Prime numbers: " + prime);
        //Print clone() return value
        System.out.println("clone() return value: " + prime.clone());
    }
}

Output Result

Prime numbers: [2, 3, 5]
clone() return value: [2, 3, 5]

In the above example, we created an ArrayList named prime. Here, we 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.

Java ArrayList Methods