Skip to content

Check If HashSet is Empty in Java Example

This example shows how to check if the HashSet is empty in Java. The example also shows how to check using the isEmpty method and size method of the HashSet class.

How to check if HashSet is empty in Java?

There are a couple of ways using which you can check if the HashSet object is empty as given below.

1. Using the isEmpty method

The isEmpty method of the HashSet class returns true if there are no elements in the HashSet object.

The isEmpty method returns false if there is at least one element in the HashSet object.

Output

2. Using the size method

You can also use the size method of the HashSet class to check the same.

If the HashSet size is 0 then the HashSet is empty, otherwise not.

Output

Which is the preferred way to check?

Let’s have a look at the Java 8 HashSet source code for both of these methods.

As we can see from the source code, both of these methods call the internal HashMap object’s isEmpty and size methods.

The HashMap isEmpty and size methods refer to the same internal size variable. So as far as performance is concerned, both of these methods will perform similarly.

However, the isEmpty method will make the code cleaner and more readable as compared to getting the size and then comparing it with the 0. That is the reason using the isEmpty method is the preferred way to check.

This example is a part of the Java HashSet Tutorial with Examples.

Please let me know your views in the comments section below.

References:
Java 8 HashSet

About the author

Leave a Reply

Your email address will not be published.