I am wondering why do HashSet uses HashMap
, TreeSet
uses TreeMap
, and LinkedHashSet
uses LinkedHashMap
internally behind the scene ? since Set
is only carrying and storing the key but the value, so isn't using extra memory space like being not economical ?
The Entry
inner class that HashMap
has is the following
class Entry<K,V> implements Map.Entry<K,V> {
final K key;
V value;
Entry<K,V> next;
final int hash;
...
....
}
For Set we don't really need that V value
variable, correct ? So what's the benefit and main reason of using a map object internally ?
Less code, less bugs, less testing.
By reusing the same code, you only need to optimize, debug and test it once. The memory overhead is minimal - another pointer for each entry, negligible compared to the Key.
Using a Map simplifies the code, but increases the memory usage slightly. It's not as much as you might think as the overhead is already high. ;)
Not all Maps have Sets and you can use the following.