This week's giveaway is in the Spring forum.
We're giving away four copies of REST with Spring (video course) and have Eugen Paraschiv on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes hashCode() and equals() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "hashCode() and equals()" Watch "hashCode() and equals()" New topic

hashCode() and equals()

Niranjan Prasad
Ranch Hand

Joined: Aug 13, 2005
Posts: 62
Why hashCode() must be overriden when equals() is overriden?
Stuart Ash
Ranch Hand

Joined: Oct 07, 2005
Posts: 637
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.

ASCII silly question, Get a silly ANSI.
subject: hashCode() and equals()
jQuery in Action, 3rd edition