jQuery in Action, 3rd edition
The moose likes Java in General and the fly likes HashCodes Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "HashCodes" Watch "HashCodes" New topic


Sudhanshu Mishra
Ranch Hand

Joined: May 28, 2011
Posts: 235

hi all,
here is a question regarding the hashCodes().Is it necessary to override hashcode() after overriding equals() or do we have to do so only for hashMap-using collections?

Matthew Brown

Joined: Apr 06, 2010
Posts: 4544

Yes, you should. If you don't you are breaking the contract for the hashCode() and equals() methods as specific in the java.lang.Object class. HashMaps and HashSets make use of that contract, but other code might as well. There's no way you can guarantee that your class will never be used in a way that makes use of the contract, so you should follow it. Especially since it's not particularly difficult (in fact, modern IDEs will do it for you!).

By not doing, you are in effect "lying" about the specification of your class, as far as other developers are concerned.
I agree. Here's the link: http://aspose.com/file-tools
subject: HashCodes
It's not a secret anymore!