What is the LinkedHashSet.clear method in Java?

The LinkedHashSet is similar to the HashSet, except that LinkedHashSet maintains the insertion order of elements, whereas HashSet does not. Read more about LinkedHashSet here.

You can use the clear method to remove all elements from the LinkedHashSet object.

Syntax

public void clear()

This method doesn’t take any parameters and doesn’t return a value.

Code

import java.util.LinkedHashSet;
class isEmpty {
public static void main( String args[] ) {
LinkedHashSet<Integer> set = new LinkedHashSet<>();
set.add(1);
set.add(2);
set.add(3);
System.out.println("The set is " + set);
System.out.println("set.isEmpty : " + set.isEmpty());
System.out.println("\nCalling set.clear()");
set.clear();
System.out.println("\nThe set is " + set);
System.out.println("set.isEmpty : " + set.isEmpty());
}
}

Explanation

In the code above, we:

  • Line #1: Import the LinkedHashSet class.

  • Line #4: Create a new LinkedHashSet object with the name set.

  • Line #5 to 7: Use the add method to add three elements(1, 2, 3) to the set object.

  • Line #10: Use the isEmpty method to check if the set is empty. In our case, the method returns false because the set contains three elements.

  • Line #13: Use the clear method to remove all the elements of the set. After calling this method, the set becomes empty, and now the isEmpty method will return true.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources