Win a copy of Escape Velocity: Better Metrics for Agile Teams this week in the Agile and Other Processes 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Tim Cooke
  • Paul Clapham
  • Jeanne Boyarsky
Sheriffs:
  • Ron McLeod
  • Frank Carver
  • Junilu Lacar
Saloon Keepers:
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Al Hobbs
  • Carey Brown
Bartenders:
  • Piet Souris
  • Frits Walraven
  • fred rosenberger

Why override default hashCode() ?

 
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If the default hashCode() produces distinct values for each object created
why do we need to override it when using Maps ?
If two objects having same instances are created naturally equals() ( which is overriden ) will return false and will not get stored in a map.
So is not efficient enough to just override equals() for high performance ( fast access ) because each object is in a distinct 'bucket' and searching and comparing with just one object in the 'bucket' is required ?
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The contract for equals() and hashCode() is that when equals() returns true when comparing two objects, then hashCode() must return the same value for those two objects. So objects that are equal must have the same hash code (see the API documentation of the hashCode() method in class Object, which explains this).

If you have overridden equals(), then you must also override hashCode() to make sure that this contract isn't broken. How you must implement hashCode() in such a case depends on how you implemented the equals() method.

It's not just for performance reasons that you need to override hashCode() if you've overridden equals() - it's because you must make sure that the contract as described above isn't broken.

If your class does break the contract, then unpredictable things might occur if you store instances of your class in a collection that uses hash codes (such as HashSet or HashMap).
[ September 10, 2007: Message edited by: Jesper Young ]
 
I RELEASE YOU! (for now .... ) Feel free to peruse this tiny ad:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic