Java LinkedList clear() Method Tutorial

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

What is Java LinkedList clear() Method?

The Java LinkedList clear() method is used to clear the entire elements of a LinkedList object.

After calling this method, the entire elements of such an object will be removed and its size (the number of elements) will return to 0.

Java 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 does not throw an exception.

Example: using LinkedList clear() method

import java.util.LinkedList;
class Main{
    public static void main(String[] args) {
        LinkedList<String> list = new LinkedList<>();
        list.add("John");
        list.add("Omid");
        list.add("Jack");
        list.add("Ellen");
        list.add("Barack");
        list.add("Ian");
        list.add("Paul");
        
        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 after calling the clear method: "+list.size());
    }
}

Output:

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

The size of the list after calling the clear method: 0
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies