*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes overriding 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 » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "overriding hashcode and equals." Watch "overriding hashcode and equals." New topic
Author

overriding hashcode and equals.

Aneek Banerjee
Ranch Hand

Joined: Jun 20, 2012
Posts: 61

Is it always necessary to override hashcode if I try to override equals?
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4344
    
    8

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: 30138
    
150

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
 
Consider Paul's rocket mass heater.
 
subject: overriding hashcode and equals.
 
Similar Threads
Doubt Regarding HashSet
if we override hashCode method is compulsary to override equals method and viseversa.
enums
Doubt about hashcode() and equals()?
A question about "equals"