• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Ron McLeod
  • paul wheaton
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
  • Himai Minh
Bartenders:

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

 
Ranch Hand
Posts: 689
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 VI Editor Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic