| Author |
is it mandatory to override equals method when overriding hashCode method
|
mahajan amit
Greenhorn
Joined: Oct 16, 2008
Posts: 14
|
|
Hello
We know that it is mandatory to override hashcode if equals method is overriden.
Is the reverse also true?
|
 |
Stephan van Hulst
Bartender
Joined: Sep 20, 2010
Posts: 3050
|
|
|
There should be no reason to override hashCode, other than to make it comply to the equals contract. Why would you ever want to do this?
|
 |
Richard Tookey
Ranch Hand
Joined: Aug 27, 2012
Posts: 362
|
|
mahajan amit wrote:
We know that it is mandatory to override hashcode if equals method is overriden.
Only mandatory if one is going to use it as a key in one of the inbuilt hash based collections. If one is just searching a List then one does not need the hash code, just the equals() method.
Note - I always make the hash code and equals() method conform so I don't get caught out.
|
 |
Ashish R Garg
Greenhorn
Joined: Jan 15, 2009
Posts: 8
|
|
In strict sense, technically its not mandatory. Neither overriding Hashcode when equals is overriden or vice versa.
But, on design level, there is a contract between equals and hashcode. Whenever equals method confirms two objects as same, they should return the same hashcode too. But its not the other way around.
Therefore its a good programming practice to override hashcode as well if you decide to override equals method.
In case you are overriding hashcode only, its your choice to override equal or not for your own sake.
Just FYI : Hashcode helps in efficient hashing for Hashmap and other such collections, while equals confirm the equalness of two objects actual value per se.
|
Never settle for less. Never Quit.
|
 |
Winston Gutkowski
Bartender
Joined: Mar 17, 2011
Posts: 4750
|
|
mahajan amit wrote:We know that it is mandatory to override hashcode if equals method is overriden.
It's only mandatory if your object might be used in a hashed collection. However, since hashed collections allow any kind of object, it does make sense.
Personally, I regard equals() and hashCode() as conjoined twins:
If I override one, I override the other; and if I change one, I also change the other to match.
It just makes life a lot easier, even if it isn't theoretically required in all cases.
Winston
|
Isn't it funny how there's always time and money enough to do it WRONG?
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32675
|
|
Welcome to the Ranch Ashish R Garg.
|
 |
 |
|
|
subject: is it mandatory to override equals method when overriding hashCode method
|
|
|