Java LinkedList clear() Method Example

The clear() method of java.util.LinkedList class will remove all the content of the LinkedList

Signature

public void clear()

This method removes all of the elements from this list..

Example

The following example shows the usage of java.util.LinkedList.clear() method.

import java.util.LinkedList;

public class ClearMethodLinkedListExample {
	public static void main(String args[])
	{
		// create an empty LinkedList
		LinkedList<String> l = new LinkedList<String>();
		
		// use add() method to add elements to the LinkedList
		l.add("Element1");
		l.add("Element2");
		l.add("Element3");

		System.out.println("Size of the List before clear -- "+l.size());
		
		//Printing the elements of the LinkedList
		System.out.println("Elements of the list before clear");

		for(String temp:l)
		{
			System.out.println(temp);
		}
		
		//Removing the all the contents of the LinkedList 
		l.clear();
		
		System.out.println("Size of the List After clear -- "+l.size());
		
		//Printing the elements of the LinkedList
		System.out.println("Elements of the list after clear");
		for(String temp:l)
		{
			System.out.println(temp);
		}
	}
}

Output

Size of the List before clear -- 3
Elements of the list before clear
Element1
Element2
Element3
Size of the List After clear -- 0
Elements of the list after clear

Leave a Reply

Your email address will not be published. Required fields are marked *