This week's book giveaway is in the Mac OS forum.
We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes HashCode Defination Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "HashCode Defination" Watch "HashCode Defination" New topic

HashCode Defination

Mohit G Gupta
Ranch Hand

Joined: May 18, 2010
Posts: 634

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 ?

OCPJP 6.0 93%
OCPJWCD 5.0 98%
Abimaran Kugathasan
Ranch Hand

Joined: Nov 04, 2009
Posts: 2066

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.

|BSc in Electronic Eng| |SCJP 6.0 91%| |SCWCD 5 92%|
Christophe Verré

Joined: Nov 24, 2005
Posts: 14688

And don't forget to SayThanks You're leaving quite a lot of threads unanswered.

[My Blog]
All roads lead to JavaRanch
Prasad Kharkar
Ranch Hand

Joined: Mar 07, 2010
Posts: 444

well there is great example in the K & B

consider hashcode as a bucket where all the objects can be put
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
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

SCJP 6 [86%], OCPWCD [84%], OCEJPAD [83%]
If you find any post useful, click the "plus one" sign on the right
Mohit G Gupta
Ranch Hand

Joined: May 18, 2010
Posts: 634

GeeCON Prague 2014
subject: HashCode Defination