• 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

hashCode and equals

 
Ranch Hand
Posts: 162
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi, This is from K&B mock exam.

If class Dog follows the equals and hashCode contracts, and if x and y are reference variables
for two Dog objects, which statements are true? (Choose all that apply.)
Correct Answer
C: If x.equals(y) is true, then x == y may be false.
E: If x.equals(y) is false, then (x.hashCode() == y.hashCode()) may be true.

EXPLANATION:

C and E are correct. C is correct because equals() can be less strict than ==. E is correct
because hashCode() can be less strict than equals().

I am not clear on the explanation. Could you please elaborate on this ? I am getting confused.
 
Bartender
Posts: 6663
5
MyEclipse IDE Firefox Browser Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

If x.equals(y) is true, then x == y may be false.



Two objects may be equals but may not represent the same object. The == test is made for objects which point to the same reference. Two dogs with the same name and ID for example may be represented by 2 different instances of the Dog class or by the same instance.

If x.equals(y) is false, then (x.hashCode() == y.hashCode()) may be true.



When 2 objects are not equal, their hashCodes can be equal or unequal. There is no contract that governs this.
reply
    Bookmark Topic Watch Topic
  • New Topic