Win a copy of The Journey To Enterprise Agility this week in the Agile and Other Processes forum! And see the welcome thread for 20% off.
  • 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:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
Sheriffs:
  • Paul Clapham
  • Junilu Lacar
  • Knute Snortum
Saloon Keepers:
  • Ron McLeod
  • Ganesh Patekar
  • Tim Moores
  • Pete Letkeman
  • Stephan van Hulst
Bartenders:
  • Carey Brown
  • Tim Holloway
  • Joe Ess

Overriding hashCode()  RSS feed

 
Ranch Hand
Posts: 634
Chrome Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
String and Wrappers class override the equals and hashCode method ,
if we need to use any class in a hashmap,we have to override the above 2 methods.

equals() method provides the equality of the objects ,then why do we need to override the hashCode method ?


 
Sheriff
Posts: 9613
37
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hash based collections like HashMap use hashCode method for faster searching and organization of elements. The equals method is only called if the hashCode matches. There are tons of tutorials on this like this, this and this...
 
Ranch Hand
Posts: 2066
Clojure IntelliJ IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
HashSet doesn't allow duplicate elements, in order to check it,
1) It uses object's hashCode() method, if those values are different, then those object are belonging to different buckets. And Those are different objects.
2) If hashCode() method returns same values for two object, then they belongs to same bucket, it further go to check that they are different or not by invoking equals() method. If both return same boolean value, those two object are same. Only one of them can be in the HashSet.

It's up to us(programmers) to implements the hashCode() method and equlas() method to work appropriately.

Further, have a look on K&B's book for the hashCode() contract and equals() method contract.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!