What is the LinkedHashSet.clear method in Java?
The
LinkedHashSetis similar to theHashSet, except thatLinkedHashSetmaintains the insertion order of elements, whereasHashSetdoes not. Read more aboutLinkedHashSethere.
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
LinkedHashSetclass. -
Line #4: Create a new
LinkedHashSetobject with the nameset. -
Line #5 to 7: Use the
addmethod to add three elements(1, 2, 3) to thesetobject. -
Line #10: Use the
isEmptymethod to check if thesetis empty. In our case, the method returnsfalsebecause thesetcontains three elements. -
Line #13: Use the
clearmethod to remove all the elements of theset. After calling this method, thesetbecomes empty, and now theisEmptymethod will returntrue.