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 ?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With