Help coderanch get a
new server
by contributing to the fundraiser
  • 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
  • Ron McLeod
  • Paul Clapham
  • Devaka Cooray
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Tim Moores
  • Carey Brown
  • Mikalai Zaikin
Bartenders:
  • Lou Hamers
  • Piet Souris
  • Frits Walraven

Test Question Clarification

 
Greenhorn
Posts: 9
2
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Took the Ch. 11 Practice Test in the OCA/OCP Java SE8 Programmer Practice Tests book and just want to understand the logic when thinking through the answer for #34  --

Question 34: How many of the following pairs of values can fill in the blanks to comply with the contract of the hashCode() and equals() methods?



I. 1, false
II. 1, true
III. new Random().nextInt(), false
IV. new Random().nextInt(), true

A. None
B. One
C. Two
D. Three

When looking at the above code where there is only one line for each option, would it always be 'None' because there is no option to return 'false' if a null object is passed in?
 
Master Rancher
Posts: 4966
78
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Correct.   You always need to return false for null, and true for the same object - that is, x.equals(x) is always true unless x is null.  So "None" is the only acceptable option listed.
 
Marshal
Posts: 79632
380
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
It may appear that you could write true, but that will violate one of the terms of the contract, symmetry, and probably some other terms. You can end up with System.out.println(x.equals(y)); printing true, and System.out.println(y.equals(x)); printing false
 
author & internet detective
Posts: 41964
911
Eclipse IDE VI Editor Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Ooh good observation. I've added this to the errata and credited you.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic