aspose file tools*
The moose likes Java in General and the fly likes Why HashCode implementation should be same as equals() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Why HashCode implementation should be same as equals()" Watch "Why HashCode implementation should be same as equals()" New topic
Author

Why HashCode implementation should be same as equals()

Sudarshan Muramreddy
Greenhorn

Joined: Jun 08, 2004
Posts: 16
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

Joined: Jul 08, 2003
Posts: 24187
    
  34

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.


[Jess in Action][AskingGoodQuestions]
Sudarshan Muramreddy
Greenhorn

Joined: Jun 08, 2004
Posts: 16
Thanks for clarification Hill.
Jessica Sant
Sheriff

Joined: Oct 17, 2001
Posts: 4313

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 ]

  • - Jess
    Blog:KnitClimbJava | Twitter: jsant | Ravelry: wingedsheep
     
     
    subject: Why HashCode implementation should be same as equals()