Easy Tutorial
❮ Java Inner Class Java Hashmap Replaceall ❯

Java ArrayList clone() Method

Java ArrayList

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

>

Extended Information:

A shallow copy duplicates the pointer to an object, not the object itself. The new and old objects still share the same memory. Therefore, if one object modifies this address, it affects the other object.

A shallow copy contrasts with a deep copy, which copies an object completely from memory, creating a new area in the heap for the new object. Modifying the new object does 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:

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 array
        ArrayList<String> sites = new ArrayList<>();

        sites.add("Google");
        sites.add("tutorialpro");
        sites.add("Taobao");
        System.out.println("Website List: " + sites);

        // Copy the sites array
        ArrayList<String> cloneSites = (ArrayList<String>)sites.clone();
        System.out.println("Copied ArrayList: " + cloneSites);
    }
}

Executing the above program outputs:

Website List: [Google, tutorialpro, Taobao]
Copied ArrayList: [Google, tutorialpro, Taobao]

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

(ArrayList<String>)sites.clone();

Output the return value of the clone() method

Example

import java.util.ArrayList;

class Main {
    public static void main(String[] args){

        // Create an array
        ArrayList<String> sites = new ArrayList<>();

        sites.add("Google");
        sites.add("tutorialpro");
        sites.add("Taobao");
        System.out.println("Website List: " + sites);

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

Executing the above program outputs:

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

In the example above, we created an ArrayList named sites and output the return value of the clone() method.

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

Java ArrayList

❮ Java Inner Class Java Hashmap Replaceall ❯