1. Introduction

In Java, the ArrayList class offers a method called clear() that is used to remove all of the elements from the list. The clear() method does not delete the list itself, instead, it just removes all elements, making the list empty. This post will guide you through the process of using the clear() method to empty an ArrayList in Java.

2. Program Steps

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

2. Print the original ArrayList.

3. Use the clear() method to remove all elements from the ArrayList.

4. Print the ArrayList again to show that it is empty.

3. Code Program

import java.util.ArrayList;
import java.util.List;

public class ArrayListClear {

    public static void main(String[] args) {

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

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

        // Step 3: Use the clear() method to remove all elements from the ArrayList
        fruitList.clear();

        // Step 4: Print the ArrayList again to show it is empty
        System.out.println("ArrayList after clear: " + fruitList);
    }
}

Output:

Original ArrayList: [Apple, Banana]
ArrayList after clear: []

4. Step By Step Explanation

Step 1: We create an ArrayList named fruitList and add two elements, "Apple" and "Banana", to it.

Step 2: We print the original ArrayList, which outputs: "Original ArrayList: [Apple, Banana]".

Step 3: The clear() method is called on fruitList to remove all of its elements. After this step, fruitList is empty.

Step 4: We print the ArrayList again to confirm that it is empty. The output is: "ArrayList after clear: []".