This week's book giveaway is in the Java 8 forum.
We're giving away four copies of Java 8 in Action and have Raoul-Gabriel Urma, Mario Fusco, and Alan Mycroft 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 Java 8 in Action this week in the Java 8 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()
Similar Threads
equals & hashcode doubt
Detecting Duplicates in Hashmap
Map Object to HashMap
Collections : Help Needed
HashSet ordering