This week's book giveaway is in the JavaFX forum.
We're giving away four copies of Introducing JavaFX 8 Programming and have Herbert Schildt on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes K&B Master Exam hashCode() Question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Introducing JavaFX 8 Programming this week in the JavaFX forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "K&B Master Exam hashCode() Question" Watch "K&B Master Exam hashCode() Question" New topic

K&B Master Exam hashCode() Question

Edisandro Bessa
Ranch Hand

Joined: Jan 19, 2006
Posts: 584
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 ?


"If someone asks you to do something you don't know how to, don't tell I don't know, tell I can learn instead." - Myself
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
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

Joined: Jan 30, 2000
Posts: 18671
For whatever reason this doesn't seem to be in the errata yet, but see past discussion here.

"I'm not back." - Bill Harding, Twister
Edisandro Bessa
Ranch Hand

Joined: Jan 19, 2006
Posts: 584
Thank you very much for your prompt replies.
I agree. Here's the link:
subject: K&B Master Exam hashCode() Question
jQuery in Action, 3rd edition