• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

HashCode and Equals

 
Ram Chhabra
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

Thanks,
Ram
 
Doug Braidwood
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Doug, clarified
 
Dennis Grimbergen
Ranch Hand
Posts: 159
IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic