Does adding a duplicate value to a HashSet/HashMap replace the previous value

前端 未结 8 1532
迷失自我
迷失自我 2020-12-02 07:14

Please consider the below piece of code:

HashSet hs = new HashSet();
hs.add(\"hi\"); -- (1)
hs.add(\"hi\"); -- (2)

hs.size() w

相关标签:
8条回答
  • 2020-12-02 07:53

    It the case of HashSet, it does NOT replace it.

    From the docs:

    http://docs.oracle.com/javase/6/docs/api/java/util/HashSet.html#add(E)

    "Adds the specified element to this set if it is not already present. More formally, adds the specified element e to this set if this set contains no element e2 such that (e==null ? e2==null : e.equals(e2)). If this set already contains the element, the call leaves the set unchanged and returns false."

    0 讨论(0)
  • 2020-12-02 07:55

    In the case of HashMap, it replaces the old value with the new one.

    In the case of HashSet, the item isn't inserted.

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