The
LinkedHashSet
is similar to theHashSet
, except thatLinkedHashSet
maintains the insertion order of elements, whereasHashSet
does not. Read more aboutLinkedHashSet
here.
You can use the clear
method to remove all elements from the LinkedHashSet
object.
public void clear()
This method doesn’t take any parameters and doesn’t return a value.
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());}}
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
.