wood burning stoves 2.0*
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


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "HashCodes" Watch "HashCodes" New topic
Author

HashCodes

Sudhanshu Mishra
Ranch Hand

Joined: May 28, 2011
Posts: 215

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?
Thanks....
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4338
    
    7

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.
 
Don't get me started about those stupid light bulbs.
 
subject: HashCodes
 
Similar Threads
Inquisition qustion regarding equals() and hashCode()
Overriding equals() and hashcode()
identical hashcode values
doubts in equals and hashCode
hash code