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

前端 未结 8 1570
迷失自我
迷失自我 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:50

    HashMap basically contains Entry which subsequently contains Key(Object) and Value(Object).Internally HashSet are HashMap and HashMap do replace values as some of you already pointed..but does it really replaces the keys???No ..and that is the trick here. HashMap keeps its value as key in the underlying HashMap and value is just a dummy object.So if u try to reinsert same Value in HashMap(Key in underlying Map).It just replaces the dummy value and not the Key(Value for HashSet).

    Look at the below code for HashSet Class:

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

    Here e is the value for HashSet but key for underlying map.and key is never replaced. Hope i am able to clear the confusion.

提交回复
热议问题