Java HashSet vs HashMap

后端 未结 7 1772
长发绾君心
长发绾君心 2020-12-12 16:13

I understand that HashSet is based on HashMap implementation but is used when you need unique set of elements. So why in the next code when putting

相关标签:
7条回答
  • 2020-12-12 16:55

    Answer is simple because it is nature of HashSets. HashSet uses internally HashMap with dummy object named PRESENT as value and KEY of this hashmap will be your object.

    hash(simpleObject1) and hash(simplObject2) will return the same int. So?

    When you add simpleObject1 to hashset it will put this to its internal hashmap with simpleObject1 as a key. Then when you add(simplObject2) you will get false because it is available in the internal hashmap already as key.

    As a little extra info, HashSet use effectively hashing function to provide O(1) performance by using object's equals() and hashCode() contract. That's why hashset does not allow "null" which cannot be implemented equals() and hashCode() to non-object.

    0 讨论(0)
提交回复
热议问题