When we call
HashSet set = new HashSet();
set.add(1);
the add
method will internally call the put
method of map with value
map.put(1,PRESENT);
.
Why is PRESENT
passed as a dummy value in map.put
?
When we call
HashSet set = new HashSet();
set.add(1);
the add
method will internally call the put
method of map with value
map.put(1,PRESENT);
.
Why is PRESENT
passed as a dummy value in map.put
?
From a conceptual point, a Map represents a superset of a Set: it contains all the keys of a Set.
Thus, it is very well possible to implement a Set by re-using a Map. But of course a Map needs a key plus a value.
So: when you decide to implement a Set by re-using a Map, adding a key to the set results in adding a key plus a dummy value to that map. And it is useful to use a non-null value, so that you can later decide whether removing a specific key actually removed anything.
Because in the implementation of HashSet
, a Map
is used to remember which values the set contains. Or, to put it in other words, which value is present.
So in order to store the Set
's values, each value is put into the Map
as a key. Since the value behind the key does not matter, a dummy value is used. That dummy value is very simple and small in order to minimize memory footprint:
private static final Object PRESENT = new Object(); //from HashSet's sourcecode
If you check the instantiation of a HashSet
:
public HashSet() {
map = new HashMap<>();
}
It's represented as a hashmap
, the values you add to the set are added as keys
to the map with dummy object values, that's how HashSet
avoids duplications