HashMap put() 和 get() 方法如何工作的内部原理(仅限基本逻辑) [英] Internals of how the HashMap put() and get() methods work (basic logic only )
问题描述
当我们使用 put()
方法在 HashMap
类中放置一个键实例表示key"和一个 Value 实例表示value"时,HashMap
类在内部做.当我们说 hashMap.get(key)
时它是如何取回值的?
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)
?
编辑:我不想在这里详细说明,主要是想了解大局以及equals()
和hashcode()
put()
和 get()
操作中的方法.
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.
推荐答案
如果你说更高的图片,就像下面一样.这里我将 item 称为 Map
的 key
代码>
If you talk about higher picture it is just like below.Here i refer item as a key
of Map
放置物品时.
- 计算key的
hashcode
- 如果存在带有该
hashcode
的basket
则在键上使用equals
方法搜索该篮子中的键以确定元素将被添加或替换. - 如果没有,则创建新的篮子(重新散列)并将该元素添加到其中.
- Calculate
hashcode
of key - If
basket
with thathashcode
is present then use theequals
method on the key search the keys i that basket to determine if the element is to be added or replace. - If not there then create new basket (rehashing) and add that element to that.
获取:
- 获取key的
hashcode
- 去那个篮子
- 在键上使用
equals
进行迭代将返回该篮子中的元素.
- Get the
hashcode
of key - Go to that basket
- Iterate using
equals
on the key will return you that element from that basket.
这篇关于HashMap put() 和 get() 方法如何工作的内部原理(仅限基本逻辑)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!