Reputation: 99
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.
Upvotes: 2
Views: 838
Reputation: 20061
Yes, you are correct. The answers to this SO question go into more detail:
Internal implementation of java.util.HashMap and HashSet
Upvotes: 2