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?

Upvotes: 4

Views: 1082

Answers (2)

user207421
user207421

Reputation: 311054

Now, I want to retrieve value associated to key "b".

OK.

I will call hm.get("b").

That's all you have to do.

Since, hashmap searches key/value pair based on hashcode of key. Hashmap will find 209 hashcode for key "b".

Correct. Or whatever the hashcode for "b" is.

Since, same hashcode is found for key "a", Hashmap may return value "aValue" instead of expected value "bValue"

No. You are mistaken. It already works correctly. You don't have to worry about it.

Upvotes: 0

Eran
Eran

Reputation: 394146

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.

Upvotes: 8

Related Questions