2

I have a question about how add method in the HashSet works. I am relatively new to Java so please don't mind if this too naive. I was looking into the source code for HashSet and found that the 'add' method in the HashSet is saving the values in a HashMap.

public boolean More ...add(E e) { return map.put(e, PRESENT)==null; } 

What I figured out is that the 'e' is the key and the add method adds the new element as a key and not as a value and thus the HashSet will have no duplicates.Please correct me if I am wrong.

7
  • 3
    You are right. I know the excitement of looking at Java source code is uncontrollable at times but seriously, what's the question now? Commented Jun 2, 2015 at 13:00
  • 1
    You know it already... If you want to dig deep... Follow the link... javahungry.blogspot.com/2013/08/… Commented Jun 2, 2015 at 13:01
  • 1
    That's basically correct. It just uses the same value PRESENT for all the entries. Nobody cared to create a separate hash set implementation, instead the existing HashMap code was reused (even though it takes more memory to store those references to the PRESENT object). Commented Jun 2, 2015 at 13:01
  • 4
    Good job for actually going into core java code yourself to see what is going on. Commented Jun 2, 2015 at 13:04
  • 1
    @DhrubojyotiBhattacharjee Yes, that's essentially what happens - PRESENT is used as a dummy value. Commented Jun 2, 2015 at 13:06

1 Answer 1

2

Yes, you are correct. The answers to this SO question go into more detail:

Internal implementation of java.util.HashMap and HashSet

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.