Check If the LinkedHashSet is Empty in Java Example

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.

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

Output

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.

Output

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.

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

About the author

RahimV

RahimV

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 *

Online Shopping