• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Overriding hashCode()

 
Ranch Hand
Posts: 634
Eclipse IDE Chrome Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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: 9707
43
Android Google Web Toolkit Hibernate IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
IntelliJ IDE Clojure Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
They worship nothing. They say it's because nothing is worth fighting for. Like this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic