Check If Hashtable is Empty in Java Example

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.

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.


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.


Which method should I use to check?

Let’s have a look at the source code of both of these methods.

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.

Java 8 Hashtable Documentation

About the author



My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

Your email address will not be published. Required fields are marked *