• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

hashCode and equals

 
Saibabaa Pragada
Ranch Hand
Posts: 162
  • Mark post as helpful
  • send pies
  • 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.
 
Deepak Bala
Bartender
Posts: 6663
5
Firefox Browser Linux MyEclipse IDE
  • Mark post as helpful
  • send pies
  • 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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic