Hashmap 以及它是如何在幕后工作的 [英] Hashmap and how this works behind the scene

查看:38
本文介绍了Hashmap 以及它是如何在幕后工作的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

快速提问以确保我理解 Java 中的 HashMap 的工作原理.

quick question to be sure I understood well how HashMap in java works.

下面是代码示例:

//String key = new String("key");
//String val = new String("value");
String key = "key";
String val = "value";

HashMap map = new HashMap();
map.put(key, val);

System.out.println("hashmap object created. Its key hashcode = "+key.hashCode());
// the hashcode is 106079
System.out.println("hashmap object value for key = "+map.get(key));

// Let's store using a key with same hashcode
Integer intkey = new Integer(106079);
val = "value2";
map.put(intkey, val);
System.out.println("hashmap object created. Its intkey hashcode = "+intkey.hashCode());
// this returns 106079 once again. So both key and intkey have the same hashcode

// Let's get the values
System.out.println("hashmap object value for intkey = "+map.get(intkey));
System.out.println("hashmap object value for key = "+map.get(key));

返回值符合预期.我在幕后读到,HashMap 的工作原理如下:

the returned values are as expected. I read that behind the scene, HashMap works as follows:

  1. 获取键/值.
  2. 根据密钥生成哈希码.
  3. 将键和值对象存储在存储桶中(在我的情况下,存储桶编号为 106079)

第二个也一样.

  1. 将其存储在同一个存储桶中,但由于此时这是一个 LinkedList,我想将其存储在下一个可用分配"中.

得到它:

  1. 拿起钥匙,获取哈希码,
  2. 看看桶,
  3. 然后从 LinkedList 中的第一个元素开始查看键,
  4. 然后检查 key 是否传递和元素中的 key 是否匹配,如果不匹配,则继续下一个,依此类推,直到可以检索到 value.

我是否正确理解了这个概念?

Am I understanding this concept correctly?

非常感谢!

非常感谢,请完成:- Java HashMap 如何在内部存储条目- Java HashMap 如何处理具有相同哈希码的不同对象?

many thanks, so to complete: - How does Java HashMap store entries internally - How does a Java HashMap handle different objects with the same hash code?

还有:

  • 不应该有那么多桶"
  • 存储桶与条目不同.存储桶是共享同一存储桶#的所有条目的逻辑集合(在 Java 案例中是键的 hashCode() 的函数).如其他答案所述,桶溢出可以通过多种方式实现,不一定是在列表中.
  • 还有其他现有的冲突解决方案:http://en.wikipedia.org/wiki/Hash_table#Collision_resolution
  • 它使用 Object 的 equals 方法来比较和检索同一桶中的对象.

推荐答案

另外请注意,HashMap 可以通过多种方式实现哈希码 冲突解决,不仅仅是你提到的使用链表

Please also note, there are several ways HashMap can implement hash codes collision resolution, not only utilizing linked list as you mentioned

Java 的 HashMap 实现不仅使用 LinkedList 策略来处理具有相同 key.hashCode() 值的键值.

Java's HashMap implementation does not only use LinkedList strategy to handle key-values with same key.hashCode() values.

另外,您可能想阅读 这个 文章

Also, you may want to read this article

这篇关于Hashmap 以及它是如何在幕后工作的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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