This example shows how to check if the LinkedHashSet object is empty in Java. The example also shows how to check if it is empty using the isEmpty method and size method.
How to check if the LinkedHashSet is empty in Java?
There are a couple of ways using which we can check if the LinkedHashSet object is empty as given below.
1. Using the isEmpty method
The isEmpty
method of the LinkedHashSet class returns true if the linked hash set object is empty.
1 |
public boolean isEmpty() |
The isEmpty
method returns false if there is at least one element in the linked hash set object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import java.util.LinkedHashSet; public class CheckIfLinkedHashSetIsEmpty { public static void main(String[] args) { LinkedHashSet<Integer> lhSetNumbers = new LinkedHashSet<Integer>(); /* * To check if the LinkedHashSet is empty or not, use * the isEmpty method */ //this will return true System.out.println( lhSetNumbers.isEmpty() ); //add elements lhSetNumbers.add(22); lhSetNumbers.add(44); //this will return false now System.out.println( lhSetNumbers.isEmpty() ); } } |
Output
1 2 |
true false |
2. Using the size method
We can also check the same using the LinkedHashSet size method. The size
method returns the number of elements contained in the linked hash set object. If the return value of the size
method is 0 then the linked hash set is empty otherwise, it is not empty.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import java.util.LinkedHashSet; public class CheckIfLinkedHashSetIsEmpty { public static void main(String[] args) { LinkedHashSet<Integer> lhSetNumbers = new LinkedHashSet<Integer>(); /* * We can also get the size of the LinkedHashSet * object and compare it with zero to check. */ //this will return true System.out.println( lhSetNumbers.size() == 0 ); //add elements lhSetNumbers.add(22); lhSetNumbers.add(44); //this will return false now System.out.println( lhSetNumbers.size() == 0 ); } } |
Output
1 2 |
true false |
What is the preferred way to check if the LinkedHashSet is empty?
The LinkedHashSet class internally maintains a HashMap object for storing the elements. Let’s have a look at the LinkedHashSet class source code for both of these methods.
1 2 3 |
public int size() { return map.size(); } |
1 2 3 |
public boolean isEmpty() { return map.isEmpty(); } |
As we can see from the source code, both the size
method and isEmpty
method call the size
and isEmpty
methods of the internal HashMap object respectively. The size
method and isEmpty
methods of the HashMap use the same internal size reference.
So as far as performance is concerned, using any of the methods will not make much difference. However, the isEmpty
method makes the code more clean and readable as compared to using the size
method for this purpose.
This example is a part of the Java LinkedHashSet Tutorial with Examples.
Please let me know your views in the comments section below.
References:
Java 8 LinkedHashSet