File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes HashCode and Equals Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "HashCode and Equals" Watch "HashCode and Equals" New topic

HashCode and Equals

Ram Chhabra

Joined: Jun 23, 2007
Posts: 23
I have read that if two objects are equal according to the equals() method, they must have the same hashCode() value (although the reverse is not generally true).

Can someone please explain this statement bit more with an example.

Doug Braidwood
Ranch Hand

Joined: Apr 04, 2010
Posts: 42
There can be many objects which are not equal() but which return the same hashcode() but you can never have two objects which are equal() with different hashcode()

For example consider a name object, where two names are equal() if they have the same first name and last name. The hashcode() could be simply to take the first letter of the last name. So you are filing all the names alphabetically into 26 'buckets'.

Ram Chhabra goes into the 'C' bucket and so does Dave Charles. They both have the same hashcode() but they are not equal().

Ram Chhabra

Joined: Jun 23, 2007
Posts: 23
Thanks Doug, clarified
Dennis Grimbergen
Ranch Hand

Joined: Nov 04, 2009
Posts: 159

In addition to this, always override hashCode() when you override equals() in your own classes. I will show you with a piece of code what happens when you don't. It will prevent your class from working correctly when you use a hash-based collection, such as a HashMap.

Here is the bad code:

And here is the better code:

Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46349
Beware: the instanceof operator can cause subtle and nasty errors when you inherit from that Person class. Google for Angelika Langer java equals or go through Joshua Bloch's book; it used to be possible to find a sample chapter including equals() on the net somewhere.
I agree. Here's the link:
subject: HashCode and Equals
jQuery in Action, 3rd edition