This example shows how to check if the Hashtable is empty in Java. This example also shows how to check if the Hashtable is empty using the isEmpty method and size method.
How to check if Hashtable is empty in Java?
There are a couple of ways using which we can check if the hash table object is empty or not.
1. Using the isEmpty method
The Hashtable isEmpty
method returns true if there are no entries in the hash table object.
1 |
public boolean isEmpty() |
It returns true if there are no keys mapped to values in the hash table object. It returns false if there is at least one key mapped to the value in the hash table.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
import java.util.Hashtable; public class CheckIfHashtableIsEmptyExample { public static void main(String[] args) { Hashtable<Integer, String> htNumbers = new Hashtable<Integer, String>(); /* * To check if the hashtable is empty or not, * use the isEmpty method */ //this will return true as there are no key-values System.out.println("Is empty? " + htNumbers.isEmpty()); //add couple of mappings htNumbers.put(10, "Ten"); htNumbers.put(11, "Eleven"); //this will return false as there are two mappings System.out.println("Is empty? " + htNumbers.isEmpty()); } } |
Output
1 2 |
Is empty? true Is empty? false |
2. Using the size method
We can also use the size
method to check if the hash table is empty or not. The size
method returns the number of entries contained in the hash table object.
We can compare the return value of the size
method with zero to check if it is empty or not.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
Hashtable<Integer, String> htNumbers = new Hashtable<Integer, String>(); /* * We can also use the size method * to check the same */ //this will return true as there are no key-values System.out.println("Is empty? " + ( htNumbers.size() == 0)); //add couple of mappings htNumbers.put(10, "Ten"); htNumbers.put(11, "Eleven"); //this will return false as there are two mappings System.out.println("Is empty? " + ( htNumbers.size() == 0)); |
Output
1 2 |
Is empty? true Is empty? false |
Which method should I use to check?
Let’s have a look at the source code of both of these methods.
1 2 3 |
public synchronized boolean isEmpty() { return count == 0; } |
1 2 3 |
public synchronized int size() { return count; } |
As we can see from the source code, both of these methods refer to the same internal count variable. As far as performance is concerned, both of the methods should perform the same.
However, using the isEmpty
method makes the code more readable and cleaner as compared to using the size
method for this purpose.
This example is a part of the Hashtable in Java Tutorial with Examples.
Please let me know your views in the comments section below.
References:
Java 8 Hashtable Documentation