Java List clear() Method Tutorial

In this section, we will learn what the List clear() method is and how to use it in Java.

What is Java List clear() Method?

The Java List clear() method is used to clear the elements of a List object altogether.

Basically, after applying this method, the target list won’t have any element left in it. Hence, its size becomes 0.

Java List clear() Method Syntax:

public void clear()

clear () Method Parameters:

The method does not take an argument.

clear () Method Return Value:

The return value of this method is void.

clear () Method Exceptions:

The method throws `UnsupportedOperationException` if the target list object does not support the method.

Example: using List clear () method

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

public class Main {

    public static void main(String[] args){
        List<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(3);
        System.out.println("The size of the list before calling the clear method: "+list.size());
        list.clear();
        System.out.println("The size of the list is: "+list.size());
    }
}

Output:

The size of the list before calling the clear method: 3

The size of the list is: 0

As you can see, calling the clear() method would remove the entire elements of a list object.
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies