What is the LinkedList.clear method in Java?

Linked list

A linked list is a collection of linear data elements. Each element (node) contains data and reference parts. The data part has the value, and the reference part has the address link to the next element. The elements are not indexed so random access is not possible. Instead, we traverse from the beginning of the list to access the elements.

In Java, the LinkedList is a doubly-linked listThis is a type of linked list. Each node contains three fields. It has two link fields (one for the previous element and another for the next element) and one data field. implementation of the List and Deque interfaces. The LinkedList class is present in the java.util package.

What is the clear method of the LinkedList class?

The clear method can be used to delete all the elements of the LinkedList. After calling this method, the list becomes empty.

Syntax

public void clear();

This method doesn’t take any parameters and doesn’t return any value.

Code

The code below demonstrates the use of the clear method:

import java.util.LinkedList;
class LinkedListClear {
public static void main( String args[] ) {
LinkedList<String> list = new LinkedList<>();
list.add("1");
list.add("2");
list.add("3");
System.out.println("The list is " + list);
list.clear();
System.out.println("After calling the clear method the list is " + list);
}
}

Explanation

In the code above:

  • In line 1, we import the LinkedList class.
import java.util.LinkedList;
  • In line 4, we create a LinkedList object named list.
LinkedList<String> list = new LinkedList<>();
  • In lines 5-7, we use the add method of the list object to add three elements("1","2","3") to the list.
list.add("1");
list.add("2");
list.add("3");
  • In line 10, we use the clear method of the list object to remove all the list elements.
list.clear();

After calling the clear method, the list becomes empty.

Free Resources