LinkedList clear() Method in Java
The Java.util.LinkedList.clear() method is used to remove all the elements from a linked list. Using the clear() method only clears all the element from the list and not deletes the list. In other words we can say that the clear() method is used to only empty an existing LinkedList.
Syntax:
void clear()
Parameters: This function does not accept any parameter.
Return Value: This method does not return any value.
Below program illustrate the Java.util.LinkedList.clear() method:
// Java code to illustrate boolean clear() import java.io.*; import java.util.LinkedList; public class LinkedListDemo { public static void main(String args[]) { // Creating an empty LinkedList LinkedList<String> list = new LinkedList<String>(); // Using add() method to add elements in the list list.add( "Geeks" ); list.add( "for" ); list.add( "Geeks" ); list.add( "10" ); list.add( "20" ); // Displaying the List System.out.println( "Original LinkedList:" + list); // Clearing the list list.clear(); // Accessing the List after clearing it System.out.println( "List after clearing all elements: " + list); // Adding elements after clearing the list list.add( "Geeks" ); list.add( "for" ); list.add( "Geeks" ); // Displaying the List System.out.println( "After adding elements to empty list:" + list); } } |
Output:
Original LinkedList:[Geeks, for, Geeks, 10, 20] List after clearing all elements: [] After adding elements to empty list:[Geeks, for, Geeks]
Recommended Posts:
- LinkedList set() Method in Java
- LinkedList add() Method in Java
- LinkedList contains() Method in Java
- LinkedList pop() Method in Java
- LinkedList get() Method in Java
- LinkedList removeFirstOccurrence() Method in Java
- LinkedList remove() Method in Java
- LinkedList removeLastOccurrence() method in Java with Example
- LinkedList spliterator() method in Java
- LinkedList removeLast() Method in Java
- LinkedList push() Method in Java
- LinkedList getFirst() Method in Java
- LinkedList getLast() Method in Java
- LinkedList toArray() method in Java with Example
- LinkedList addFirst() Method in Java
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.