Languages
[Edit]
EN

Java - how to get element from HashSet?

6 points
Created by:
Tehya-Blanchard
474

1. Overview

Edit

In java Set / HashSetLinkedHashSet don't have get method.

Ofcourse it is possible to 'GET' element from Set in java, we just need to think a bit different when using this data structure. What I mean by this?

When we want to GET element from Set in java we just need to check if Set contains the object we want to get. So we already have our element we want to get from HashSet, the only think left to do is to check if Set have this object inside by using contains method with correctly implemented hashCode() and equals().

HashSet internally uses HashMap and contains method on HashSet calls HashMap containsKey method.

Internally HashSet uses HashMap which looks like this:

We can go inside JDK and check it by ourselves.

The best way to understand what I mean is by analyzing below 2 examples.

When we use intellij IDEA we can just click on contains method and attach the debugger inside.

2. Example 1 - HashSet with String

Edit

This example uses String, String have internal hashCode and equals implemented in JDK.

Output:

String - Internal hashCode and equals implemented in JDK.

HashSet - contains JDK implementation (as we can see HashSet internally uses HashMap)

3. Example 2 - HashSet with custom User objects

Edit

In this example we implement explicit hashCode and equals for User class.

When we invoke contains method

Output:

 

1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Java Collections - HashSet

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join