Why do Set data structures in Java use Map interna

2019-04-28 22:41发布

问题:

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 ?

回答1:

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.



回答2:

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.

Set<T> set = Collection.newSetFromMap(new ConcurrentHashMap<T>());
Set<T> set = Collection.newSetFromMap(new ConcurrentSkipListMap<T>());
Set<T> set = Collection.newSetFromMap(new IdentityHashMap<T>());