• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Bear Bibeault
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • Devaka Cooray
Saloon Keepers:
  • Ganesh Patekar
  • Tim Moores
  • Carey Brown
  • Stephan van Hulst
  • salvin francis
Bartenders:
  • Ron McLeod
  • Frits Walraven
  • Pete Letkeman

why should i need to override hashcode when i override equals method  RSS feed

 
Ranch Hand
Posts: 689
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi, why should i override hashcode method when i override equals method?

and can any one provide me a program how it really needs ?
thanks in advance
 
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because two instances returning different hashcodes won't be equal.
A foolish example. equals() always returns true, but "c" is not found.

 
Sheriff
Posts: 3341
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are three methods that are closely related, each may be used by different Collection type to determine equality.
equals
hashCode
compareTo (For Sorted Collection, you must implement the Comparable innerface)

For your object to function in the various Collections as documented, the following rule should be followed.

hashCode will return the same value and compareTo will return 0 when equals returns true

If your objects will never participate in hash based collections or sorted collections, it's not necessary to follow that rule however, it will either limit what you can do or result in unexpected results.

I've seen this in one project. TreeSet is documented to contain one and one one of any object which equas is true. However, following the rule above, it actually uses compareTo returning 0 to do this. On this job someone wrote compareTo in a way inconsistant with the rule and as a result, doubles where going in and some objects where apparently randomly being excluded from the TreeSet.

Unless you have a large complelling reason to not follow the rules, I recommend you make it a habit. And any time you diviate prepare for some unexpected results.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!