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

data-structures, hashmap, hashtable, java

Solution

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

While Putting items.

- Calculate `hashcode` of key

- 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.

- If not there then create new basket (rehashing) and add that element to that.

Get:

- Get the `hashcode` of key

- Go to that basket

- Iterate using `equals` on the key will return you that element from that basket.

Problem

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.

Original source

Related problems