java - How does HashSet not allow duplicates? -


i going through add method of hashset. mentioned

if set contains element, call leaves set unchanged , returns false.

but add method internally saving values in hashmap

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

the put method of hashmap states

associates specified value specified key in map. if map contained mapping key, old value replaced.

so if put method of hashmap replaces old value, how hashset add method leaves set unchanged in case of duplicate elements?

present dummy value -- set doesn't care is. set does care map's keys. logic goes this:

set.add(a):   map.put(a, present) // far, said     key "a" in map, so...       keep "a" key, map value present passed in       also, return old value (which we'll call old)   @ return value: it's old, != null. return false. 

now, fact old == present doesn't matter -- , note map.put doesn't change key, value mapped key. since map's keys set cares about, set unchanged.

in fact, there has been change underlying structures of set -- replaced mapping of (a, old) (a, present). that's not observable outside set's implementation. (and happens, change isn't real change, since old == present).


Comments

Popular posts from this blog

c# - How to get the current UAC mode -

postgresql - Lazarus + Postgres: incomplete startup packet -

angularjs - ng-repeat duplicating items after page reload -