This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin for Android App Development and have Peter Sommerhoff on-line!
See this thread for details.
Win a copy of Kotlin for Android App Development this week in the Kotlin forum!
  • 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 ...
  • Campbell Ritchie
  • Liutauras Vilda
  • Devaka Cooray
  • Jeanne Boyarsky
  • Bear Bibeault
  • Junilu Lacar
  • Paul Clapham
  • Knute Snortum
Saloon Keepers:
  • Ron McLeod
  • Tim Moores
  • Stephan van Hulst
  • salvin francis
  • Carey Brown
  • Tim Holloway
  • Frits Walraven
  • Ganesh Patekar

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
Posts: 14691
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.

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.
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.
All of the world's problems can be solved in a garden - Geoff Lawton. Tiny ad:
RavenDB is an Open Source NoSQL Database that’s fully transactional (ACID) across your database
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!