Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

overriding hashcode and equals.

 
Aneek Banerjee
Ranch Hand
Posts: 61
Eclipse IDE Java Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is it always necessary to override hashcode if I try to override equals?
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You should do, yes. The contract says that if two objects are equal then they should have the same hash code (but not necessarily the other way round). So if you redefine equals() you should redefine hashCode() to match.
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 34973
379
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Not "you should.". You "must."

The JavaDoc says
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.


If you don't override hashCode when you've overwritten equals, you will get unpredictable behavior at times. T he only exception is when you "overwrite" equals with:

Do you know why this is a special case?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic