Win a copy of Modern JavaScript for the Impatient this week in the Server-Side JavaScript and NodeJS forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Bear Bibeault
  • Junilu Lacar
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • salvin francis
  • Frits Walraven
Bartenders:
  • Scott Selikoff
  • Piet Souris
  • Carey Brown

Regarding Hashcode and Equals

 
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
 
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.
 
And will you succeed? Yes you will indeed! (98 and 3/4 % guaranteed) - Seuss. tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
    Bookmark Topic Watch Topic
  • New Topic