clear() method

clear() method: This Clear function in Java method is used to remove all the elements from the LinkedHashSet. Its return type is void. It means this method doesn’t returns anything.

void clear();
import java.util.LinkedHashSet;
public class ExampleOfLinkedHashSet 
{
	public static void main(String[] args) 
	{
		LinkedHashSet<String> listOfNames = new 
                LinkedHashSet<String>();
		
		listOfNames.add("JAVA");
		listOfNames.add("GOAL");
		listOfNames.add("RAVI");
		listOfNames.add("SITE");
		
		// Before clear() method
		for(String name : listOfNames)
		{
		   System.out.println("Name from list = "+name);
		}
		
		// Removing all the element by clear() method
		listOfNames.clear();
		
		System.out.println("After Clear() method list is 
                empty : "+ listOfNames.isEmpty());
	}
}

Output: Name from list = JAVA
Name from list = SITE
Name from list = GOAL
Name from list = RAVI
After Clear() method list is empty : true

Leave a Comment