Please consider the below piece of code:
HashSet hs = new HashSet();
hs.add(\"hi\"); -- (1)
hs.add(\"hi\"); -- (2)
hs.size()
w
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.