<分区>
快速提问以确保我很好地理解 Java 中的 HashMap 是如何工作的。
这是一个代码示例:
//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 的工作方式如下:
- 获取键/值。
- 根据 key 生成哈希码。
- 将键和值对象存储在桶中(在我的例子中,桶号为 106079)
第二个也是一样。
- 将它存储在同一个桶中,但由于此时这是一个 LinkedList,我想将它存储在“下一个可用分配”中。
获取方式:
- 拿起 key ,获取哈希码,
- 看看水桶,
- 然后查看 LinkedList 中第一个元素的键,
- 然后检查传递的键和元素中的键是否匹配,如果不匹配则继续下一个,依此类推直到可以检索到值。
我对这个概念的理解是否正确?
非常感谢!
编辑:
非常感谢,所以要完成: - 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 方法比较和检索同一桶中的对象。