Win a copy of Escape Velocity: Better Metrics for Agile Teams this week in the Agile and Other Processes forum!
  • 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
  • Liutauras Vilda
  • Tim Cooke
  • Paul Clapham
  • Jeanne Boyarsky
Sheriffs:
  • Ron McLeod
  • Frank Carver
  • Junilu Lacar
Saloon Keepers:
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Al Hobbs
  • Carey Brown
Bartenders:
  • Piet Souris
  • Frits Walraven
  • fred rosenberger

Doubt in K&B SCJP 5: mock exam question on equals()/hashCode() contract

 
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This one is another proof by contradiction.

The question:


The answer claims that two do:

C:


The above is fine and will fulfill the contract.

D


Of course, the contract basically boils down to, "when o1.equals(o2) is true, o1.hashCode() == o2.hashCode() must also return true.

The above is claimed to be correct, but actually FAILS to fulfill the contract, because it will return true at times that hashCode() will return false. For instance, whenever rate and bal are flipped between the two objects being compared. See the following:



If executed, the above will print "Equals returns true but hashCode returns false". Therefore, D does not fulfill the contract and should be considered an incorrect response.
 
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 you may find a discussion of this in the errata.
 
Justin Seconi
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I checked https://coderanch.com/t/257589/java-programmer-SCJP/certification/SCJP-Errata-Updated first, but I didn't find anything that seemed to reference it. (As far as I know, the question is only on the MasterExam/LearnKey application exam).
 
When it is used for evil, then watch out! When it is used for good, then things are much nicer. Like this tiny ad:
The trailboss has a kickstarter
https://coderanch.com/t/754577/Garden-Master-kickstarter
reply
    Bookmark Topic Watch Topic
  • New Topic