File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Regarding Hashcode and Equals 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 "Regarding Hashcode and Equals" Watch "Regarding Hashcode and Equals" New topic

Regarding Hashcode and Equals

chander shivdasani
Ranch Hand

Joined: Oct 09, 2007
Posts: 206

I want to know how Equals and Hashcode is actually used when we are adding/fetching data into/from collections, say HashMap.

for Adding we provide a key and value pair and for fetching we provide just a key.So how the elements are stored using hashcode and how they are fetched using Equals and hashcode. I tried searching a lot in the internet, but still i cannot understand the working. I am clear with the working of Hashcode and Equals method and their contract. If you can explain with a simple example then it will be helpful.


Enjoy, Chander
SCJP 5, Oracle Certified PL/SQL Developer
Ian Edwards
Ranch Hand

Joined: Aug 14, 2006
Posts: 107
The K&B book has a useful analogy on how hashcode and equals are used in the storage and retrieval of objects in a collection.

Suppose you have a number of buckets in which your objects are going to be stored. The hashcode() method determines which bucket the object would go in to. As you will know different objects can end up with the same hashcode and thus would go into the same bucket as a different object.

When it comes to retrieving the object the hash code would tell us which bucket it is in. When it comes to finding the object that we are after we use the equals() method to go through the different objects to find the one we want.

Hope this helps.
I agree. Here's the link:
subject: Regarding Hashcode and Equals
It's not a secret anymore!