How does HashSet not allow duplicates?

后端 未结 6 1978
情歌与酒
情歌与酒 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:39

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

    e is the key, So if e is already present put will not return null. Hence add will return false.

    JavaDoc for put :

    the previous value associated with key, or null if there was no mapping for key. (A null return can also indicate that the map previously associated null with key.)

提交回复
热议问题