aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Doubt regarding equals() and hashCode() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Doubt regarding equals() and hashCode()" Watch "Doubt regarding equals() and hashCode()" New topic
Author

Doubt regarding equals() and hashCode()

Nitin Kumar
Greenhorn

Joined: Apr 18, 2005
Posts: 29
In the chapter 'Collection's in K&B book, it is written many a times that

statement 1 " if x.equals(y) is true, then x.hashCode() == y.hashCode() "

and

Statement 2 "If you override equals() then override hashCode() ;

But the following code, which is also from K&B book, page 546, runs fine even though hashCode() method doesn't return same value and is not overwritten




this code gives output of " One and two are equal ". Two things that are confusing for me are :
a) Even if the hashCode() is not overwritten then how come two instances ( one and two) are equal ( seems to violate statement 2 )
b) Two instances are equal but one.hashCode() and two.hashCode() are not equal. ( seems to violate statement 1 )

After doing some more search I came to the conclusion that the above statements, are ONLY valid if the concerned classes are used in Collection Framework, i,e in Maps,Sets, Lists and Queues.

Could you please let me know if the above conclusion is correct or I am missing something.

Thanks


Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9302
    
  17

After doing some more search I came to the conclusion that the above statements, are ONLY valid if the concerned classes are used in Collection Framework, i,e in Maps,Sets, Lists and Queues.

Yes you are right, if you break the equals-hashCode contract (i.e. for equal objects hashCode is different etc), then the objects might not work correctly with collections (more specifically hash based collections like HashSet, HashMap etc) because they need the hashCode and equals method to identify elements correctly for retrieval from the collection...


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Nitin Kumar
Greenhorn

Joined: Apr 18, 2005
Posts: 29
Hi Ankit,

Thanks for the confirmation ...
saima kanwal
Ranch Hand

Joined: Oct 05, 2009
Posts: 148
Does it mean that when we write a class in which we break the contract for hashcode and equals , our code will still compile and run??


SCJP 6.0 (86%) SCWCD 5 (94%)
Wouter Oet
Saloon Keeper

Joined: Oct 25, 2008
Posts: 2700

Why don't you try it?


"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Doubt regarding equals() and hashCode()