Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do Set data structures in Java use Map internally?

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 ?

like image 582
peter Avatar asked Sep 14 '12 20:09

peter


People also ask

Does Set internally uses map?

Now as you can see that whenever we create a HashSet, it internally creates a HashMap and if we insert an element into this HashSet using add() method, it actually call put() method on internally created HashMap object with element you have specified as it's key and constant Object called “PRESENT” as it's value.

Which data structure HashMap uses internally & Why?

HashMap contains an array of the nodes, and the node is represented as a class. It uses an array and LinkedList data structure internally for storing Key and Value.

Why do we use map interface in Java?

This method is used to clear and remove all of the elements or mappings from a specified Map collection. This method is used to check whether a particular key is being mapped into the Map or not. It takes the key element as a parameter and returns True if that element is mapped in the map.

How does map work internally in Java?

Internally HashMap uses a hashCode of the key Object and this hashCode is further used by the hash function to find the index of the bucket where the new entry can be added. HashMap uses multiple buckets and each bucket points to a Singly Linked List where the entries (nodes) are stored.


1 Answers

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.

like image 75
zmbq Avatar answered Nov 09 '22 20:11

zmbq