aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes equals() and hashCode contract Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "equals() and hashCode contract" Watch "equals() and hashCode contract" New topic
Author

equals() and hashCode contract

Bon Thanh
Greenhorn

Joined: Nov 18, 2009
Posts: 17
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

Joined: Oct 08, 2009
Posts: 276
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.


OCJP 6 (93%)
Dejan Miler
Ranch Hand

Joined: Nov 14, 2009
Posts: 56
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

SCJP 1.6 in progress ....
Bon Thanh
Greenhorn

Joined: Nov 18, 2009
Posts: 17
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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: equals() and hashCode contract