LinkedList clear() Method in Java
Last Updated :
13 Dec, 2024
Improve
In Java, the clear() is used to remove all the elements from a LinkedList. This method only clears all the element from the list and not deletes the list. After calling this method, the list will be empty.
Syntax of LinkedList clear() Method
void clear()
- Parameters: This method does not accept any parameter.
- Return type: This method does not return any value.
Example: Here, we use the clear() method to remove elements from the LinkedList.
// Java programm to demomstrate the
// working of clear() in LinkedList
import java.util.LinkedList;
public class GFG {
public static void main(String args[]) {
// Creating an empty LinkedList
LinkedList<String> l = new LinkedList<>();
// Using add() method to add
// elements in the LinkedList
l.add("Geeks");
l.add("for");
l.add("Geeks");
System.out.println("Original LinkedList: " + l);
// Clearing the LinkedList
l.clear();
// Accessing the LinkedList
// after clearing it
System.out.println(
"List after clearing all elements: " + l);
}
}
Output
Original LinkedList: [Geeks, for, Geeks] List after clearing all elements: []