Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

HashCode Defination

 
Mohit G Gupta
Ranch Hand
Posts: 634
Chrome Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The equals() algorithm must be at least as precise in defining what
"meaningfully equivalent" means as the hashCode() method is.


what does this statement exactly mean ?
 
Abimaran Kugathasan
Ranch Hand
Posts: 2066
Clojure IntelliJ IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't know, what is the intention of the author of that statement. But, generally, there is a contract between the hashCode() and equals() method for an object. We/developers should satisfy them in order to proper usages.
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And don't forget to SayThanks You're leaving quite a lot of threads unanswered.
 
Prasad Kharkar
Ranch Hand
Posts: 446
1
Eclipse IDE MySQL Database Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

well there is great example in the K & B

consider hashcode as a bucket where all the objects can be put
now
suppose we are putting Strings and the alphabets are given the numbers from 1 to 26
hashcode method defines the formula such that if the addition of the number allotted to all the letters is same
then the objects should be put in the same bucket
here
we take four names Alex, Dirk, Bob and Fred
Alex = 1 + 12 + 5 + 24 = 42
bob = 2 + 15 + 2 = 19 = 19
dirk = 4 + 9 + 18 + 11 = 42
Fred = 6 + 18 + 5 + 4 = 33

so this is our formula
and objects with equal hashcodes will go into same bucket

so here Alex and Dirk will go into the same bucket

now when we are implementing equals method
then it will check for the hashcode first
that means, the objects will be equal if the addition of numbers is equal
and they are in the same order
that means
for objects being equal, hashcodes SHOULD be equal

so, when we want to search equal objects, then objects with the same hashcode will be
searched instead of searching and calculating that value for all the objects

this increases the efficiency of program

hope this helps

 
Mohit G Gupta
Ranch Hand
Posts: 634
Chrome Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
THanks
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic