• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why HashCode implementation should be same as equals()

 
Sudarshan Muramreddy
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,
I know we need to Override the hashcode() method when ever we override equals() method of object,and even we need to provide same implementation for the two methods.

Can any one tell me why we need to have same implementation for both methods.


Thanks in advance,
Sudarshan
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, the simplest answer: because the Javadoc for Object.hashCode() says:


If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.


If you override either equals() or hashCode(), then in general, this requirement will no longer be met by the default implementation of the other method. Therefore other code that depends on this behavior -- in particular, HashMaps and the like -- will break.

Josh Bloch has a whole section on this in his Effective Java, which is an essential book to have.
 
Sudarshan Muramreddy
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for clarification Hill.
 
Jessica Sant
Sheriff
Posts: 4313
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you only implement the .hashcode() method -- you'll be able to insert objects into a HashTable.

BUT, if you don't implement the .equals() method -- you won't be able to get objects out of a HashTable.

Check out this example from the Programming Puzzler's session at JavaOne 2002 (Josh Bloch and Neal Gafter).

Look at this code, what's the result?


So, what does it print?
(a) true
(b) false
(c) It varies

----------------------------------------

It varies --> Donald is in the set, but the set can’t find him
The Name class violates the hashCode contract

How do you fix it?
Add a hashCode method:


The moral of the story:
  • Override hashCode when overriding equals
  • Obey general contracts when overriding
  • See Effective JavaTM, Chapter 3
    [ July 01, 2004: Message edited by: Jessica Sant ]
  •  
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic