# HashCode Defination

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

SCJP 6 [86%], OCPWCD [84%], OCEJPAD [83%]

If you find any post useful, click the "plus one" sign on the right