Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrive values when collision occured in HashMap?

How will I get the value associated with the key?

Suppose, my code is written like below:

Hashmap hm = new Hashmap();`

hm.put("a","aValue"); // Suppose hashcode created for key "a" is 209

hm.put("b","bValue"); // Here hashcode created for key "b" is 209 as well.

Now, I want to retrieve value associated to key "b". I will call hm.get("b"). Since, hashmap searches key/value pair based on hashcode of key. Hashmap will find 209 hashcode for key "b". Since, same hashcode is found for key "a", Hashmap may return value "aValue" instead of expected value "bValue"

So, here is my question, I want to retrieve value associated with key. How will I do that?

like image 889
Rajasekharareddy Satti Avatar asked Oct 18 '25 12:10

Rajasekharareddy Satti


1 Answers

HashMap knows how to handle multiple keys having the same hashCode. As long as the two keys are not equal to each other (using equals of the class the keys belong to), HashMap can distinguish between them even if they share the same hashCode.

When two distinct keys have the same hashCode, they are stored in a linked list structure in the map index that corresponds with the hashCode. When you search for one of the keys (by calling get or containsKey), the HashMap would locate the map index that corresponds with the the hashCode and search the entries in the linked list sequentially, using equals to identify the requested key.

like image 127
Eran Avatar answered Oct 22 '25 05:10

Eran