Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

hashCode() and equals()

 
Niranjan Prasad
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why hashCode() must be overriden when equals() is overriden?
 
Stuart Ash
Ranch Hand
Posts: 637
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Niranjan Prasad:
Why hashCode() must be overriden when equals() is overriden?


Because they both go hand-in-hand to determine the unique identity of an object. By definition, every object that is unique has a unique hash code, and every two objects that are equal have the same hash code.

Thus, if you are implementing your own way of testing equality, this consistency must still be maintained, for which you must also implement the hashCode() based on your specific logic for that class, such that the above requirements still hold.

Hope this clarifies it.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic