When we put a key instance say "key" and a Value instance say "value" in a HashMap
class using put()
method , what does the HashMap
class do internally . How does it retrieve the value back when we say hashMap.get(key)
?
Edit: I do not want details here , basically trying to understand the bigger picture and the role of equals()
and hashcode()
method in put()
and get()
operations.
It is a data structure that allows us to store object and retrieve it in constant time O(1) provided we know the key. In hashing, hash functions are used to link keys and values in HashMap. Objects are stored by the calling put(key, value) method of HashMap and retrieved by calling the get(key) method.
HashMap uses its static inner class Node<K,V> for storing map entries. That means each entry in hashMap is a Node . 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.
get() method in HashMapget() method is used to get the value by its Key. It will not fetch the value if you don't know the Key. When get(K Key) method is called, it calculates the hash code of the Key. Suppose we have to fetch the Key "Aman." The following method will be called.
HashMap uses equals() to compare the key to whether they are equal or not. If the equals() method return true, they are equal otherwise not equal. A single bucket can have more than one node, it depends on the hashCode() method. The better your hashCode() method is, the better your buckets will be utilized.
If you talk about higher picture it is just like below.Here i refer item as a key
of Map
While Putting items.
hashcode
of key basket
with that hashcode
is present then use the equals
method on the key search the keys i that basket to determine if the element is to be added or replace.Get:
hashcode
of keyequals
on the key will return you that element from that basket.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