• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

Regarding Hashcode and Equals

 
Ranch Hand
Posts: 206
Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 107
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic