Check If Element Exists in Java HashSet Example (contains)

This example shows how to check if an element exists in HashSet in Java. This example also shows how to check if the HashSet contains the element using the contains method.

How to check if element exists in Java HashSet using the contains method?

The contains method of the HashSet class returns true if the specified object exists in the HashSet.

The contains method returns true if the HashSet contains the specified element, false otherwise.

Output

How to check if an object of a custom class exists in the HashSet?

The HashSet contains method relies on the equals and hashCode methods to check if the set contains the specified element. For the HashSet of custom class objects, if the custom class does not override the equals and hashCode methods then the contains method fails to find the specified object.

Output

As we can see from the output, even if the account with id 101 exists in the HashSet object, the contains method returned false. When the custom class does not override the equals and hashCode methods, methods inherited from the Object class are used. The equals method of the Object class compares the object references not the actual object content and thus returns false.

In order for the contains method to work properly, we need to implement the equals and hashCode methods in our custom class as given below.

Output

As we can see from the output, this time the contains method returned true as expected.

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

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

References:
Java 8 HashSet

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