This week's book giveaway is in the Performance forum.
We're giving away four copies of The Java Performance Companion and have Charlie Hunt, Monica Beckwith, Poonam Parhar, & Bengt Rutisson on-line!
See this thread for details.
Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

SJCP - equals() question

 
Colin Hillman
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One of the mock questions in the MasterExam allows these two implementations of equals() (I've commented out the first)



I agree with the commented out version, but aren't there values for rate and bal which would break the hashcode contract for the uncommented version - if rate=1 and bal=2 in one object and rate=2 and bal=1 in the other? That way, equals would return true but hashcode false, assuming code has a non-empty string - or am I missing something?

Does anyone know if errata has been produced for MasterExams (from the Sierra and Bates CDROM)?
[ May 31, 2008: Message edited by: Colin Hillman ]
 
Campbell Ritchie
Sheriff
Pie
Posts: 49447
62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to JavaRanch.

Just hving a quick look at those equals() methods, I think you are correct. 6 and 4 or 4 and 6 would create such errors. That method would appear capable of returning true from two SortOfs which do not encapsulate the same data.
 
Colin Hillman
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks - yes you're right, although it might be a case of "equality is in the eye of the beholder" - i.e. we can define equality on any terms.

My concern is that it breaks the hashcode() contract since in the example you gave, x.equals(y) is true, but x.hashcode() != y.hashcode(). Am I right?
 
Cyril Boulm´┐Ż
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have the same problem,

For me :

break the hashCode() contract.

Error in exam?
 
Campbell Ritchie
Sheriff
Pie
Posts: 49447
62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You will have to run some test code, but if you can find a case where you can show a.equals(b) && a.hashCode() != b.hashCode() you have demonstrated that the class breaches the contract for hashCode.

Please try it and report.

Yes, it does appear that you probably both have the same problem, obviously with the same question.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic