Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Internals of how the HashMap put() and get() methods work (basic logic only )

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.

like image 673
Geek Avatar asked Jul 19 '12 11:07

Geek


People also ask

How PUT and GET works in HashMap?

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.

How HashMap put works internally?

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.

How does get () method of HashMap work in Java?

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.

How the HashMap works internally and some more questions on it?

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.


1 Answers

If you talk about higher picture it is just like below.Here i refer item as a key of Map

While Putting items.

  1. Calculate hashcode of key
  2. If 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.
  3. If not there then create new basket (rehashing) and add that element to that.

Get:

  1. Get the hashcode of key
  2. Go to that basket
  3. Iterate using equals on the key will return you that element from that basket.
like image 149
amicngh Avatar answered Nov 14 '22 22:11

amicngh