Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Mock doubt, a Q about equals contract

 
Costa lamona
Ranch Hand
Posts: 102
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The following is from K & B Mock exam 1

if the output is "x = 1111", which of the following will always be true ?

All my answers counted as wrong, and the correct answer is
x2.equals(x1) == true;

This is an error isn't it, specially this one should always be false
if it become true, then the equals() contract will not be applied.
 
Sanjeev Singh
Ranch Hand
Posts: 381
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think this must be
x7.equals(x8) == true or x8.equals(x7) == true;
x2.equals(x1) may results to true or false.
 
Costa lamona
Ranch Hand
Posts: 102
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks

Originally posted by Sanjeev Kumar Singh:
I think this must be
x2.equals(x1) may results to true or false.


Actually, I beleive it can be true because the contrapositive of one of
the statments in the hashCode() contract is

if x.hashCode() != y.hashCode() returns true, then x.equals(y) must return false.

K & B on page 534.

Do you agree ?
 
Sanjeev Singh
Ranch Hand
Posts: 381
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I revisited the hashCode() and equal() contract.I think I have given wrong explanation.

if x.hashCode() != y.hashCode() returns true, then x.equals(y) must return false.

Yes I agree on this.So it is not neccessary that x.equals(y)must not return true.
Now coming to the original question

x3.hashCode()==x4.hashCode() must return true and
x5.hashCode()==x6.hashCode() must return true
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic