hashCode and equals methods Override

By | May 27, 2014

Why hashCode should also be overridden when equals is overridden?
This is a common question which you will be asked in java interviews. We’ll answer this question in detail . But first lets discuss some other basic questions which will help you to understand this question better What is the purpose of hashCode and equals methods? ,How hashCode and equals are implemented? Lets start.

What is the purpose of hashCode method ?
The purpose hashCode method is to provide the hashcode of an object.The default implementation of hashCode() provided by Object class is derived by mapping the memory address to an integer value.When inserting an entry in hashtable or other hash datastructures. First the hashcode of the key is calculated to find the position of entry in hashtable. However it is possible to override the hashCode method in your implementation class.

What is the purpose of equals method in java?
As the name suggests the purpose of this method is to check whether two objects are equal or not.The default implementation is to compare the addresses of two objects to determine equality.But almost all(like String,Integer etc) of the native classes override it to return two objects as equal only if there values are equal .For user defined classes if you don’t override this method then according to the default they will be considered equal only if there addresses are equal.

Why to override hashcode() if overriding equals()?
The answer to this question lies in the contract between hashCode and equals method.Here’s what it says :

  1. Teh hashcode of two equal object should always be same
  2. If two object have same hashcode they may or may not be equal

So whenever you override equals method you should override hashCode method so that it should satisfy the above contract.
We’ve tried to keep this article short and precise .Because we saw many sites serving nonsense to readers.
See our Interview Puzzles page for some interesting puzzles and give your brain a good exercise.

One thought on “hashCode and equals methods Override

  1. Pingback: Insideview Interview Questions : set1 | CrackDInterview

Leave a Reply

Your email address will not be published. Required fields are marked *