• Post Reply Bookmark Topic Watch Topic
  • New Topic

Why do I need to implement hashcode when Object already does it ?  RSS feed

 
Ali Gordon
Ranch Hand
Posts: 182
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was reading about HashMap and how the hashcode method must be implemented properly by the key Class. If Object class already does that reliably, then why do I have to care
about implementing hashcode for any custom class ? I only need to implement equals properly, right ?
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 66306
152
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because your version of equals is likely different from that of Object (or why write one at all?), and your hashcode must follow the contract that equal objects must have the same hashcode.

If this contract is not adhered to, things can go badly awry.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is a rule on how equals() and hashCode() must behave: If two objects a and b are equal (which means: a.equals(b) is true), then their hash codes must be the same (so, a.hashCode() == b.hashCode()).

If you break this rule, then your class cannot be used in a HashSet or for the keys in a HashMap.

Suppose you create a class and only override equals(), not hashCode():

Now try this:

Output:

true
21685669
2133927002


Conclusion: This class violates the equals - hashCode contract. a and b are equal, but their hash codes are different.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!