Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt about hashcode() and equals()?

 
Harivenkatesh Polnati
Greenhorn
Posts: 25
Java Oracle Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why always override hashcode() if overriding equals()?
 
Ashwini Kashyap
Ranch Hand
Posts: 90
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 10417
63
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic