When :
Object1.equals(Object2) = true at that time
Object1.hashCode() == Object2.hashCode()
But when
Object1.hashCode() == Object2.hashCode() its not required that
Object1.equals(Object2) = true.
Very less people know why! Lets unreveal the secret ;-)
Think as if you are a laundry man and you wash clothes for only one person.
Suppose you have 1000 buckets numbered on their body. Number starting from 1 onwards. Now you want to do some searching technique say you have clothes to put in the bucket. You are very smart so you want to employ some algorithm to fasten the search process. So what you do is : You see the cloth, if its Shirt you calculate its numerical value like a =1, b=2 and so on. so calculating the shirt's numerical value gives you "x" so what you do is, you put this shirt in xth bucket. Again you have a cap you want to put it. You find out its numerical value say "y" and you put cap in Yth bucket. Now you wash all the clothes and you are done.
Now your customer comes and asks only for cap. What will you do? will you search that cap in all 1000 buckets? What a loss if you do so!! So what you do is you think cap ok.... let me calculate its value it comes to "y" and you go to yth bucket and search the cap and give it to your customer you are done. This numerical value is nothing but hashCode in a way.
Now think you got 50 customers and you wash for them then? in xth bucket and yth bucket you will have 50 -50 pieces of clothes. God... Now how will you identify that this cap belongs to customer1 or customer2?
Here equals() method comes handy. You will write your own equals() method to compare if this cap is for me or its for you.
Its just an example. The algorithm which I showed you for calculating hashCode() is poor but valid ;-) it was just to explain the concept easily. In big structors we will be having powerful algorithms to calculate hashCodes.
More powerful the hashCode generation algorithm is less time time it takes for search operation. In the worst case it will be linear search (in case of pooer hashcode generating algorithm.)
In the beginning I said when 2 objects are having equal hashCode its not necessary that both objects are equal. Because say you are calculating hashCode on names say two customer names are : May and Amy both will be having same hashCode() their objects will go in same bucket. So both objects are not equal but they are having equal hashCode().
This is the reason while overriding hashCode() we override equals() also;-)
1 more thing secret to share :
Hashtable allows only the objects (as key or value) which objects have equals() and hashCode() methods(if not override these methods should be present in super class).
And this is the reason why Hashtable does not allow null values as key or values.
Friday, 18 April 2008
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment