YouTip LogoYouTip

Java Arraylist Clone

Java ArrayList clone() Method

Java ArrayList Java ArrayList

The clone() method is used to copy an ArrayList. It performs a shallow copy.

Extension:

A shallow copy only copies the pointer to an object, not the object itself. The new and old objects still share the same memory block. Therefore, if one object changes this address, it will affect the other object.

The counterpart to a shallow copy is a deep copy. A deep copy completely copies an object from memory, allocating a new area in the heap memory for the new object. Modifying the new object will not affect the original object.

The syntax for the clone() method is:

arraylist.clone()

Note: arraylist is an object of the ArrayList class.

Parameter Description:

  • None

Return Value

Returns an ArrayList object.

Example

Using the ArrayList clone() method to copy an ArrayList:

Example

import java.util.ArrayList;

class Main {
    public static void main(String[] args) {
        // Create an ArrayList
        ArrayList<String> sites = new ArrayList<>();
        sites.add("Google");
        sites.add("");
        sites.add("Taobao");

        System.out.println("Website List: " + sites);

        // Clone the sites ArrayList
        ArrayList<String> cloneSites = (ArrayList<String>)sites.clone();

        System.out.println("Cloned ArrayList: " + cloneSites);
    }
}

Running the above program outputs:

Website List: [Google, , Taobao]
Cloned ArrayList: [Google, , Taobao]

In the example above, we created an ArrayList named sites. Note the expression:

(ArrayList<String>)sites.clone();
  • sites.clone() - Returns a copy of the sites object.
  • (ArrayList<String>) - Casts the returned value to an ArrayList of type String.

Output the return value of the clone() method

import java.util.ArrayList;

class Main {
    public static void main(String[] args) {
        // Create an ArrayList
        ArrayList<String> sites = new ArrayList<>();
        sites.add("Google");
        sites.add("");
        sites.add("Taobao");

        System.out.println("Website List: " + sites);

        // Output the value returned by the clone() method
        System.out.println("clone() Return Value: " + sites.clone());
    }
}

Running the above program outputs:

Website List: [Google, , Taobao]
clone() Return Value: [Google, , Taobao]

In the example above, we created an ArrayList named sites. We then output the value returned by the clone() method.

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

Java ArrayList Java ArrayList

← Python3 String ZfillJava Arraylist Clear β†’