• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt on a K & B LearnKey CD question

 
Jisha Anand
Ranch Hand
Posts: 62
Flex Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear All,
This is a question from LearnKey CD provided along with K & B SCJP Guide:

Given:


Which of the following fulfill the equals() & hashCode() contract for this class? (Choose all that apply)

Correct Answer given are:

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

The explanation given is that the equals method must be atleast as precise as the hashCode() method.

The first option ofcourse is correct; but I don't understand how the second option is correct. I mean doesn't that break the hashCode - equals contract for cases in which code.length() of both objects compared are equal & the values of bal & rate for both are interchanged? In such cases this.hashCode() != o.hashCode(), but this.equals(o) will be true right? Confused!
Please help!

 
Rob Spoor
Sheriff
Pie
Posts: 20546
57
Chrome Eclipse IDE Java Windows
 
Jisha Anand
Ranch Hand
Posts: 62
Flex Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Rob!

Good to know I also am not on the wrong side

There are more errors in the CD questions, which I don't know whom to mail/message to; but this one I thought it's something which I overlooked.

Thanks again!
 
Campbell Ritchie
Sheriff
Pie
Posts: 49379
62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
SCJP questions and errors are usually discussed on another forum. Moving.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic