• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

K&B Master Exam hashCode() Question

 
Ranch Hand
Posts: 584
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 2412
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you very much for your prompt replies.
 
reply
    Bookmark Topic Watch Topic
  • New Topic