This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan 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 Android Security Essentials Live Lessons this week in the Android 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
Author

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 ?

Thanks.


"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
Wanderer
Sheriff

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.
 
 
subject: K&B Master Exam hashCode() Question
 
Similar Threads
K&B Master Exam Question 56
mistake in k&b hashCode()/equals() contract question
hashcode contract S&B question
Wrong Answer in Master Exam? [equals() and hashCode() Contract]
A question from Mock Test about hashCode