This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Doubt about hashcode() and equals()? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Doubt about hashcode() and equals()?" Watch "Doubt about hashcode() and equals()?" New topic
Author

Doubt about hashcode() and equals()?

Harivenkatesh Polnati
Greenhorn

Joined: Mar 17, 2012
Posts: 25

Why always override hashcode() if overriding equals()?
Ashwini Kashyap
Ranch Hand

Joined: Aug 30, 2012
Posts: 90
If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
This is clearly stated in hashCode() description.

Please refer its Object class API here for more clarity.

Thanks,
Ashwini Kashyap
Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 7552
    
  18

Harivenkatesh Polnati wrote:Why always override hashcode() if overriding equals()?

You don't have to do it, but it's basically good practise, because it ensures that your object will always work correctly in a hashed collection.

If you don't follow this rule - and that includes not just overriding hashCode(), but also ensuring that it's always in sync with equals() (ie, if you update equals(), you also need to update hashCode()) - you run the risk of someone using it in a HashMap or HashSet and having it behave very strangely.

Winston


Isn't it funny how there's always time and money enough to do it WRONG?
Articles by Winston can be found here
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Doubt about hashcode() and equals()?
 
Similar Threads
what is hashcode and equals contract?
HashSet ordering
map method containsKey
equals - hashcode
On Sets