Hashmap 及其幕后工作原理 [英] Hashmap and how this works behind the scene

查看:22
本文介绍了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. 然后检查传递的键和来自元素的键是否匹配,如果不匹配则继续下一个,依此类推,直到可以检索到值.

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

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.

此外,您可能需要阅读this 文章

Also, you may want to read this article

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

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