| 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
Saloon Keeper
Joined: Aug 03, 2008
Posts: 9189
|
|
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: 32651
|
|
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
|
 |
 |
|
|
subject: hashCode() and equals()
|
|
|