HashMap put() 和 get() 方法如何工作的内部原理(仅限基本逻辑) [英] Internals of how the HashMap put() and get() methods work (basic logic only )

查看:17
本文介绍了HashMap put() 和 get() 方法如何工作的内部原理(仅限基本逻辑)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我们使用 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 称为 Mapkey代码>

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

放置物品时.

  1. 计算key的hashcode
  2. 如果存在带有该 hashcodebasket 则在键上使用 equals 方法搜索该篮子中的键以确定元素将被添加或替换.
  3. 如果没有,则创建新的篮子(重新散列)并将该元素添加到其中.
  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.

获取:

  1. 获取key的hashcode
  2. 去那个篮子
  3. 在键上使用 equals 进行迭代将返回该篮子中的元素.
  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.

这篇关于HashMap put() 和 get() 方法如何工作的内部原理(仅限基本逻辑)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆