1.

How a value is retrieved from a HashMap?

Answer»

For retrieval or storing a value, a HashMap uses two methods of its KEY class - hashCode() and equals(). HashMap STORES its entries in a large collection of buckets which can be randomly accessed using an INDEX. To retrieve a value, first, the hashCode() method of the Key is invoked to get the hash value. This hash value is USED to identify the bucket where the value would be retrieved from. While storing an entry, there might be some scenario where the calculated hash value is the same for more than one keys. This results in to enter multiple key-value pairs in the same bucket. 

A bucket keeps its entries as a Linked List. So, while retrieving, after finding out the appropriate bucket, this linked list needs to be traversed to find the actual entry for the key. This time, the equals() method is used to compare the key of each entry in the list. Once it finds a key equal, the value from the entry is returned. There is a contract between these two methods which says if two objects are equal based on equals() method, their hashCode() value MUST be the same. So, if we plan to use objects of a class as the key of a HashMap, we should override both the methods - hashCode() and equals() so that this contract is maintained. 



Discussion

No Comment Found