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