wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes why equals() and hashCode() should override Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "why equals() and hashCode() should override" Watch "why equals() and hashCode() should override" New topic
Author

why equals() and hashCode() should override

kiran nyala
Ranch Hand

Joined: Sep 21, 2009
Posts: 42

why equals() and hashCode() should override could you please explain
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 10908
    
  12

if you don't override equals(), you inherit the one from the Object class. This does nothing more than compare if the REFERENCES are equal. You need to override the equals method so that it makes sense for your object. For example, two object of my House class may be equal if the houses are worth the same amount. Or it may make more sense for me to define it if they have the same number of bedrooms. Or if they have the same square footage.

Since you are defining the class, YOU have to decide what makes two instances 'equal', and tell the JVM how to figure that out.


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 36465
    
  15
You will find lots about it if you search this forum; questions about equals are asked about once a week, and you will find something useful. The reason for overriding hashCode too is that there are members of the collections Framework which depend on the hash code for sorting elements.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: why equals() and hashCode() should override
 
Similar Threads
Expain me what is hashCode() method
hashing
Doubt in Collections
Overriding equals() & hashcode() in collections
equals() and hashCode() from Java.Inquisition