Java Utility Library

Java LinkedList - clear() Method



The java.util.LinkedList.clear() method is used to clear all elements of the list. This method makes the list empty with a size of zero.

Syntax

public void clear()

Parameters

No parameter is required.

Return Value

void type.

Exception

NA

Example:

In the example below, the java.util.LinkedList.clear() method is used to clear all elements of the given list.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a linkedlist
    LinkedList<Integer> MyList = new LinkedList<Integer>();

    //populating linkedlist
    MyList.add(10);
    MyList.add(20);
    MyList.add(30);

    //printing linkedlist
    System.out.println("Before applying clear() method.");
    System.out.println("MyList contains: " + MyList);

    MyList.clear();

    //printing linkedlist
    System.out.println("\nAfter applying clear() method."); 
    System.out.println("MyList contains: " + MyList);   
  }
}

The output of the above code will be:

Before applying clear() method.
MyList contains: [10, 20, 30]

After applying clear() method.
MyList contains: []

❮ Java.util - LinkedList