Hashing means generating a int value for the object.
Java has given hashCode() function you can override and write your algorithm to generate this int value.
HashSet, HashMap all Hash based collection uses hashCode() to store the objects.
suppose you have a class:
Here I have written my algorithm to generate hashCode() that is the length of
String name.
You can understand working of HashMap, HashSet etc using buckets.
Suppose you are a HashMap and you have lots of buckets at your home and you have assigned numbers to all the buckets suppose 25 buckets and you have assigned number from 1 to 25.
Now
map.put(p1, "ranch hand Member # 184009");
Now first of all you will take this p1 object and call
p1.hashCode();. Calling this code you will get value 5 as "Punit" length is 5. Then you will find bucket no 5 and put this p1 in that bucket.
same for p2 and p3. Thus p2 "Kaleeswaran" will be in bucket no 11 and p3 "Karuppasamy" will also be in bucket no 11.
no 5 bucket : p1("Punit");
no 11 bucket: p2("Kaleeswaran"), p3("Karuppasamy");
Now suppose anybody wants to know the p2's status on javaranch.com, then
he will ask you by calling your method get(p2).
like: map.get(P2);
System.out.println(p2 +" is "+map.get(p2));
What will you do?
1. you will take p2 object.
2. you will call p2.hashCode() and will get 11.
3. you will find bucket no. 11. But you see that bucket 11 has 2 objects, now you are confused which object to return which one is for p2?
4. But you have an idea.
You have equals() method for rescue.
You will call p2.equals(p3_stored_in_bucket), and p2.equals(p2_stored_in_bucket).
5. You will find p2.equals(p2) return true, you will return "ranch hand Member # 152434" stored with key p2_stored_in_bucket.
[ December 19, 2008: Message edited by: punit singh ]
[ December 19, 2008: Message edited by: punit singh ]