How does HashSet not allow duplicates?

后端 未结 6 1979
情歌与酒
情歌与酒 2021-02-06 23:17

I was going through the add method of HashSet. It is mentioned that

If this set already contains the element, the call leaves t

6条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-06 23:34

    From javadocs for HashMap.put(), "Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced."

    Thus the map value will be replaced, (which is a constant static field in HashSet class, and thus the same instance is replaced), and the map key is kept untouched (which, in fact IS the Set collection item)

提交回复
热议问题