aspose file tools
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
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "overriding hashcode and equals." Watch "overriding hashcode and equals." New topic

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

Joined: Apr 06, 2010
Posts: 4518

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

Joined: May 26, 2003
Posts: 31655

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?

[OCA 8 book] [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
I agree. Here's the link:
subject: overriding hashcode and equals.