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

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 copy of number
        ArrayList<Integer> cloneNumber = (ArrayList<Integer>)number.clone();
        System.out.println("Cloned ArrayList: " + cloneNumber);
    }
}

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()

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 Number: " + prime);

        // print the return value of clone()
        System.out.println("Return value of clone(): " + prime.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.

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges