• 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

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.
 
If you have a bad day in October, have a slice of banana cream pie. And this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic