Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Regarding Hashcode and Equals

 
chander shivdasani
Ranch Hand
Posts: 206
Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

Regards,
Chander
 
Ian Edwards
Ranch Hand
Posts: 107
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic