• 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
  • Tim Cooke
  • Devaka Cooray
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Carey Brown
  • Tim Holloway
Bartenders:
  • Martijn Verburg
  • Frits Walraven
  • Himai Minh

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.
 
Hey, I'm supposed to be the guide! Wait up! No fair! You have the tiny ad!
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic