Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

K&B Master Exam hashCode() Question

 
Edisandro Bessa
Ranch Hand
Posts: 584
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi guys,

Could you please explain why option D is correct in below question :

Which of the following will fulfill the equals() and hashCode() contracts for this class ? (Choose all that apply.)

a) return ((SortOf)o).bal == this.bal;

b) return ((SortOf)o).code.length() == this.code.length();

c) return ((SortOf)o).code.length() * ((SortOf)o).bal ==
this.code.length() * this.bal;

d) return ((SortOf)o).code.length() * ((SortOf)o).bal * ((SortOf)o).rate == this.code.length() * this.bal * this.rate;

In my first attempt I chose C but according to MasterExam explanation both
C and D options are the correct answers.

I think D is not correct because supposing you have two instances of class SortOf and the folowing instance variable values :

Instance #1
------------
name : "None"
bal: 1
rate :3

Instance #2
------------
name : "None"
bal: 3
rate :1

In this case will occur the situation where the equals() method will return true when comparing both instances but hashCode() will be evaluated to false, hence breaking the contract.

Can anyone please give your comments ?

Thanks.
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I believe that this question may have been included in the errata of the book. You can ask Bert Bates for certain about that. But I do remember a thread here about that question.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For whatever reason this doesn't seem to be in the errata yet, but see past discussion here.
 
Edisandro Bessa
Ranch Hand
Posts: 584
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you very much for your prompt replies.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic