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

equals() and hashCode contract

 
Bon Thanh
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is a question from the ePractice exams for 310-055 purchased directly from Sun Microsystems.

Given:



Which two are true? (Choose two.)

A - Two instances of Sock with the same size and color will have the same hashcode.
B - Two instances of Sock with the same size and color might have different hashcodes.
C - A Hashtable that uses Sock instances as keys will always be able to successfully retrieve objects stored in it.
D - A Hashtable that uses Sock instances as keys will NOT always be able to successfully retrieve objects stored in it.

Sun's answer is:
Options B and D are correct. For Maps to work with Sock, hashCode must be properly overridden.

I disagree. According to http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Object.html: If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.

So shouldn't Option A be correct and not Option B? Please confirm.

Thank you!
Bonnie
 
Lorand Komaromi
Ranch Hand
Posts: 276
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Bon Thanh wrote: According to http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Object.html: If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.


The class above violates this contract, it doesn't override the hashcode() inherited from Object, and the value returned by Object.hashCode() probably will be different for each instance.
 
Dejan Miler
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I agree with Lorand.

This qutes are from K&B book page 632

If x.equals(y) is true, x.hashCode() == y.hashCode() is true.
If x.equals(y) is false, then x.hashCode() == y.hashCode() can be either or , but will tend to create better efficiency.


Dejan
 
Bon Thanh
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Lorand and Dejan,

I just want to be sure that I am clear about this. Since this class did not provide its own hashCode() implementation, it inherits Object's hashCode(), which will probably be different for each instance.

Hence Option B - Two instances of Sock with the same size and color might have different hashcodes. is correct?

Thanks for your patience,
Bonnie
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic