What is the LinkedHashSet.isEmpty in Java?
The
LinkedHashSetis similar to theHashSet, except thatLinkedHashSetmaintains the insertion order of elements, whereasHashSetdoes not. Read more aboutLinkedHashSethere.
The isEmpty method can be used to check if the LinkedHashSet object is
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
LinkedHashSetclass. -
On line number 4: We create a new
LinkedHashSetobject with the nameset. -
On line number 6: We use the
isEmptymethod to check if thesetis empty. In our case,trueis returned because thesetcontains no elements. -
On line number 8: We add an element
hito thesetusing theaddmethod. -
On line number 10: We use the
isEmptymethod to check if thesetis empty. In this place,falseis returned because thesetcontains one element (hi).