Win a copy of Python Continuous Integration and Delivery this week in the Python 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
  • Bear Bibeault
  • Paul Clapham
  • Jeanne Boyarsky
  • Devaka Cooray
  • Junilu Lacar
  • Tim Cooke
Saloon Keepers:
  • Tim Moores
  • Ron McLeod
  • Tim Holloway
  • Claude Moore
  • Stephan van Hulst
  • Winston Gutkowski
  • Carey Brown
  • Frits Walraven

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 ?

Posts: 9643
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.
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!