Clear LinkedList in Java


An LinkedList can be cleared in Java using the method java.util.LinkedList.clear(). This method removes all the elements in the LinkedList. There are no parameters required by the LinkedList.clear() method and it returns no value.

A program that demonstrates this is given as follows.

Example

 Live Demo

import java.util.LinkedList;
public class Demo {
   public static void main(String[] args) {
      LinkedList<String> l = new LinkedList<String>();
      l.add("Orange");
      l.add("Apple");
      l.add("Peach");
      l.add("Guava");
      System.out.println("LinkedList before using the LinkedList.clear() method: " + l);
      l.clear();
      System.out.println("LinkedList after using the LinkedList.clear() method: " + l);
   }
}

The output of the above program is as follows

LinkedList before using the LinkedList.clear() method: [Orange, Apple, Peach, Guava]
LinkedList after using the LinkedList.clear() method: []

Now let us understand the above program.

The LinkedList l is created. Then LinkedList.add() is used to add the elements to this LinkedList. The LinkedList is displayed before and after using theLinkedList.clear() method which clears the LinkedList. A code snippet which demonstrates this is as follows

LinkedList<String> l = new LinkedList<String>();
l.add("Orange");
l.add("Apple");
l.add("Peach");
l.add("Guava");
System.out.println("LinkedList before using the LinkedList.clear() method: " + l);
l.clear();
System.out.println("LinkedList after using the LinkedList.clear() method: " + l);

Updated on: 30-Jul-2019

983 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements