• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

hashCode() doubt

 
raja kanak
Ranch Hand
Posts: 135
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I got this mock question from JQPlus

I guess a,b,c,d are correct. But the answer is a,b,d,e
My doubt is how c is correct? I can't understand the logic?

Thanks for any help.
 
Matthew Alesi
Ranch Hand
Posts: 38
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is because choice c would violate the unchecked contract that equals() and hashCode() must fulfill in order for them to work properly.

One of the stipulations of this contract is that hashCode() and equals() should use the same criteria to formulate their values, or at least that equals() use all of what hashCode uses and then some more if you want. Think about it: if hashCode() came up with two different hashcodes based on different values for b in two objects of the above class, the equals() test might still return true if the a values are the same. hashCode()'s must be equal if equals() is true.

I hope I explained that well enough. Please say so if I didn't.
 
raja kanak
Ranch Hand
Posts: 135
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Matthew Alesi.
Now i understand the issue.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic