Java ArrayList clear()

The Java ArrayList clear() method removes all the elements from an arraylist.

The syntax of the clear() method is:

arraylist.clear()

Here, arraylist is an object of the ArrayList class.


clear() Parameters

The clear() method does not take any parameters.


clear() Return Value

The clear() method does not return any value. Rather, it makes changes to the arraylist.


Example 1: Remove all elements from String Type ArrayList

import java.util.ArrayList;

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

        // create an arraylist
        ArrayList<String> languages = new ArrayList<>();

        languages.add("Java");
        languages.add("JavaScript");
        languages.add("Python");
        System.out.println("Programming Languages: " + languages);

        // remove all elements
        languages.clear();
        System.out.println("ArrayList after clear(): " + languages);
    }
}

Output

Programming Languages: [Java, JavaScript, Python]
ArrayList after clear(): []

In the above example, we have created a arraylist named languages. The arraylist stores the name of programming languages.

Here, we have used the clear() method to remove all the elements of languages.


ArrayList clear() Vs. removeAll()

The ArrayList also provides the removeAll() method that also remove all elements from the arraylist. For example,

import java.util.ArrayList;

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

        // create an arraylist
        ArrayList<Integer> oddNumbers = new ArrayList<>();

        // add elements to arraylist
        oddNumbers.add(1);
        oddNumbers.add(3);
        oddNumbers.add(5);
        System.out.println("Odd Number ArrayList: " + oddNumbers);

        // remove all elements
        oddNumbers.removeAll(oddNumbers);
        System.out.println("ArrayList after removeAll(): " + oddNumbers);
    }
}

Output

Odd Number ArrayList: [1, 3, 5]
ArrayList after removeAll(): []

In the above example, we have created an arraylist named oddNumbers. Here, we can see that the removeAll() method is used to remove all the elements from the arraylist.

Both the removeAll() and clear() method are performing the same task. However, the clear() method is used more than removeAll(). It is because clear() is faster and efficient compared to removeAll().

To learn more about removeAll(), visit Java removeAll() method.