What is the LinkedHashSet.isEmpty 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.

The isEmpty method can be used to check if the LinkedHashSet object is emptycontains no elements.

Syntax

public boolean isEmpty()

Parameters

This method doesn’t take any input parameters.

Return value

This method returns true if the LinkedHashSet object is empty. Otherwise, false is returned.

Code

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

In the code above:

  • On line number 1: We import the LinkedHashSet class.

  • On line number 4: We create a new LinkedHashSet object with the name set.

  • On line number 6: We use the isEmptymethod to check if the set is empty. In our case, true is returned because the set contains no elements.

  • On line number 8: We add an element hi to the set using the add method.

  • On line number 10: We use the isEmptymethod to check if the set is empty. In this place, false is returned because the set contains one element (hi).

Free Resources