Friday, February 5, 2016

How hashCode and equals method works in HashMap or HashTable


How hashCode and equals method works in HashMap or HashTable?

Ans)  HashMap or HashTable or ConcurrentHashMap are used based on requirements when there are key value storage needed.  We should remember HashMap is backed by array in Java we will call it as bucket. 
whenever you use a get(key) method of hashcode the following are happened. 
1. Key.hashCode() method is used to find the bucket location in backing array. 
2.    In bucket, key and values are stored in form of a nested class called Entry.  If there is only one Entry at bucket location then, value from that entry is returned. 
Till now it's easy.. right? Now if the two keys has same hashcode then, we need a bit tricky to get the value for proposed key.  In this situation,  during put() operation collision had occurred, which means multiple Entry object stored in a bucket location. Each Entry keep track of another Entry, forming a  linked list data structure there.
Now the trace goes as follows,
1.   Call hashCode() method of key to find bucket location.
2.   Traverse through linked list, comparing keys in each entries using keys.equals() until it return true.
So, we use equals() method of key object to find correct entry and then return value from that. Remember key.equals() method. Many programmers mention value.equals(), which may be due to interview nervousness, but that’s incorrect. Since you don't have value object passed to get() method, there is no question of calling equals and hashCode() method on value object.  

That's it... Happy Learning!!!!