| Author |
overriding hashcode and equals.
|
Aneek Banerjee
Ranch Hand
Joined: Jun 20, 2012
Posts: 30
|
|
|
Is it always necessary to override hashcode if I try to override equals?
|
 |
Matthew Brown
Bartender
Joined: Apr 06, 2010
Posts: 3793
|
|
|
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
internet detective
Marshal
Joined: May 26, 2003
Posts: 26192
|
|
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?
|
[Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta, TOGAF part 1 and part 2
|
 |
 |
|
|
subject: overriding hashcode and equals.
|
|
|