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.

  • 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? – Chetan Kinger Jun 02 '15 at 13:00
  • 1
    You know it already... If you want to dig deep... Follow the link... http://javahungry.blogspot.com/2013/08/how-sets-are-implemented-internally-in.html – CoderNeji Jun 02 '15 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). – Tagir Valeev Jun 02 '15 at 13:01
  • 4
    Good job for actually going into core java code yourself to see what is going on. – vikingsteve Jun 02 '15 at 13:04
  • Thanks,I wanted to know that if PRESENT is used as a dummy value which the Set does not care about? – Dhrubojyoti Bhattacharjee Jun 02 '15 at 13:05
  • 1
    @DhrubojyotiBhattacharjee Yes, that's essentially what happens - `PRESENT` is used as a dummy value. – Jesper Jun 02 '15 at 13:06
  • 1
    Yes, the value of `PRESENT` is not important, only that it's not null. – Paul Jun 02 '15 at 13:07

1 Answers1

2

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

Internal implementation of java.util.HashMap and HashSet

Community
  • 1
  • 1
Paul
  • 19,704
  • 14
  • 78
  • 96