Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
204 views
in Technique[技术] by (71.8m points)

java - Internals of how the HashMap put() and get() methods work (basic logic only )

When we put a key instance say "key" and a Value instance say "value" in a HashMap class using put() method , what does the HashMap class do internally . How does it retrieve the value back when we say hashMap.get(key) ?

Edit: I do not want details here , basically trying to understand the bigger picture and the role of equals() and hashcode() method in put() and get() operations.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you talk about higher picture it is just like below.Here i refer item as a key of Map

While Putting items.

  1. Calculate hashcode of key
  2. If basket with that hashcode is present then use the equals method on the key search the keys i that basket to determine if the element is to be added or replace.
  3. If not there then create new basket (rehashing) and add that element to that.

Get:

  1. Get the hashcode of key
  2. Go to that basket
  3. Iterate using equals on the key will return you that element from that basket.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...