File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes hashCode() and equals() 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 "hashCode() and equals()" Watch "hashCode() and equals()" New topic
Author

hashCode() and equals()

Ravissant Markandey
Ranch Hand

Joined: Oct 24, 2007
Posts: 41
Hi Everyone,
I have this doubt regarding hashcodes from KATHY SEIRRA(pg.no. 534).It has a table stating the following conditions/requirements:

Condition Required
(1) x.equals(y)
== true x.hashCode() ==y.hashCode()



(2) x.hashCode() != x.equals(y) == false
y.hashCode()


Now, I have the following code:



here, the equals test for n1 and n2 holds true even when i comment the overridden hashCode() method which contradicts (1) above and hence automatically contradicts (2) as well.
Please help.

Regards,
Ravissant Markenday
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9304
    
  17

Well if you are saying that the contract is being broken, then yes it is. But what do you expect. Do you think that it will be a compiler error. If you think so than you are wrong.

The equals and hashCode contract is just a suggestion so that you can use your classes in Collections. If you don't follow the contract, you will not get any errors but will get unexpected outputs like you won't be able to find objects is hash based collections etc....


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39395
    
  28
The "contract" about equals and hashCode is more than a "suggestion." What you are doing by implementing an equals() method which overrides the Object#equals(java.lang.Object) method is telling users (implicitly) that you are fulfilling the requirements stated there. And you don't want your classes going round telling fibs to their users, do you?

But you are correct that it is specifically used in Maps and Sets.
Djonatah Stiegler
Ranch Hand

Joined: Oct 30, 2008
Posts: 32
Keep in mind that legal hashCode() override is different than an efficient override

There's an "exam watch" in that section that talks about legal and appropriate hashCode override.

Thanks
DJ.


From Brazil
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: hashCode() and equals()