• 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:
  • Campbell Ritchie
  • Bear Bibeault
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • paul wheaton
Saloon Keepers:
  • Ganesh Patekar
  • Frits Walraven
  • Tim Moores
  • Ron McLeod
  • Carey Brown
Bartenders:
  • Stephan van Hulst
  • salvin francis
  • Tim Holloway

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: 9643
42
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.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!