1. Introduction

In Java, the ArrayList class provides a method called clone(), which is used to create a shallow copy of the ArrayList. The clone() method does not clone the elements themselves but creates a new ArrayList with references to the same elements. In this post, we will demonstrate how to clone an ArrayList in Java.

2. Program Steps

1. Create an ArrayList and add some elements to it.

2. Print the original ArrayList.

3. Clone the original ArrayList using the clone() method.

4. Print the cloned ArrayList.

5. Demonstrate that the two ArrayLists are separate by modifying one and printing both again.

3. Code Program

import java.util.ArrayList;

public class ArrayListClone {

    public static void main(String[] args) {

        // Step 1: Create an ArrayList and add some elements to it
        ArrayList<String> originalList = new ArrayList<>();
        originalList.add("Apple");
        originalList.add("Banana");
        originalList.add("Cherry");

        // Step 2: Print the original ArrayList
        System.out.println("Original ArrayList: " + originalList);

        // Step 3: Clone the original ArrayList using the clone() method
        ArrayList<String> clonedList = (ArrayList<String>) originalList.clone();

        // Step 4: Print the cloned ArrayList
        System.out.println("Cloned ArrayList: " + clonedList);

        // Step 5: Demonstrate that the two ArrayLists are separate
        clonedList.add("Date");
        System.out.println("Original ArrayList after modification: " + originalList);
        System.out.println("Cloned ArrayList after modification: " + clonedList);
    }
}

Output:

Original ArrayList: [Apple, Banana, Cherry]
Cloned ArrayList: [Apple, Banana, Cherry]
Original ArrayList after modification: [Apple, Banana, Cherry]
Cloned ArrayList after modification: [Apple, Banana, Cherry, Date]

4. Step By Step Explanation

Step 1: An ArrayList named originalList is created and populated with the elements "Apple", "Banana", and "Cherry".

Step 2: The original ArrayList is printed to the console.

Step 3: The clone() method is used to create a shallow copy of the originalList, and the result is cast to ArrayList<String> and stored in a new ArrayList reference clonedList.

Step 4: The cloned ArrayList is printed to the console, showing that it contains the same elements as the original ArrayList.

Step 5: To demonstrate that originalList and clonedList are two separate ArrayList objects, an element "Date" is added to clonedList. After modification, both originalList and clonedList are printed again, showing that the originalList remains unchanged while the clonedList contains the new element.