Java HashMap
使用 put
方法在 HashMap
中插入 K/V 对。 Lets say I have used put
method and now HashMap<Integer, Integer>
has one entry with key
as 10 and value
as 17.
如果我在此插入 10,20 HashMap
由于相同的密钥 10 而导致冲突,它只是用此条目替换了之前的条目。
如果密钥冲突 HashMap
用新的 K/V 对替换旧的 K/V 对。
所以我的问题是 HashMap
什么时候使用链接冲突解决技术?
为什么它没有形成 linkedlist
键为 10,值为 17,20?
原文由 user2938723 发布,翻译遵循 CC BY-SA 4.0 许可协议
当您插入一对
(10, 17)
然后插入(10, 20)
时,技术上不涉及碰撞。您只是用给定键的新值替换旧值10
(因为在这两种情况下,10 等于 10,而且 10 的哈希码始终为 10)。当多个键散列到同一个桶时会发生冲突。在这种情况下,您需要确保可以区分这些键。链接冲突解决是用于此的技术之一。
As an example, let’s suppose that two strings
"abra ka dabra"
and"wave my wand"
yield hash codes100
and200
respectively.假设总数组大小为 10,它们最终都在同一个桶中(100 % 10
和200 % 10
)。链接可确保无论何时执行map.get( "abra ka dabra" );
,最终都会得到与密钥相关联的正确值。对于 Java 中的哈希映射,这是通过使用equals
方法完成的。