Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

hashCode() and equals()

 
Ravissant Markandey
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Everyone,
I have this doubt regarding hashcodes from KATHY SEIRRA(pg.no. 534).It has a table stating the following conditions/requirements:

Condition Required
(1) x.equals(y)
== true x.hashCode() ==y.hashCode()



(2) x.hashCode() != x.equals(y) == false
y.hashCode()


Now, I have the following code:



here, the equals test for n1 and n2 holds true even when i comment the overridden hashCode() method which contradicts (1) above and hence automatically contradicts (2) as well.
Please help.

Regards,
Ravissant Markenday
 
Ankit Garg
Sheriff
Posts: 9509
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well if you are saying that the contract is being broken, then yes it is. But what do you expect. Do you think that it will be a compiler error. If you think so than you are wrong.

The equals and hashCode contract is just a suggestion so that you can use your classes in Collections. If you don't follow the contract, you will not get any errors but will get unexpected outputs like you won't be able to find objects is hash based collections etc....
 
Campbell Ritchie
Sheriff
Posts: 48415
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The "contract" about equals and hashCode is more than a "suggestion." What you are doing by implementing an equals() method which overrides the Object#equals(java.lang.Object) method is telling users (implicitly) that you are fulfilling the requirements stated there. And you don't want your classes going round telling fibs to their users, do you?

But you are correct that it is specifically used in Maps and Sets.
 
Djonatah Stiegler
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Keep in mind that legal hashCode() override is different than an efficient override

There's an "exam watch" in that section that talks about legal and appropriate hashCode override.

Thanks
DJ.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic