Why set data structures in Java using Map inside?

I wonder why a HashSet uses a HashMap , a TreeSet uses a TreeMap , and a LinkedHashSet uses a LinkedHashMap inside behind the scene? since Set carries and stores the key, but the value, therefore, does not use additional memory space, for example, uneconomical?

The inner Entry class that the HashMap has is as follows

 class Entry<K,V> implements Map.Entry<K,V> { final K key; V value; Entry<K,V> next; final int hash; ... .... } 

For Set, we really don't need the V value variable, right? So, what is the use and the main reason for using the map object inside?

+4
source share
2 answers

Less code, fewer errors, less testing.

By reusing the same code, you only need to optimize, debug, and test it once. The memory overhead is minimal - a different pointer for each record, negligible compared to the key.

+11
source

Using a map simplifies the code, but slightly increases memory usage. This is not as much as you think, since the overhead is already high .;)

Not all Cards 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>()); 
+3
source

Source: https://habr.com/ru/post/1434294/


All Articles