Java HashMap中的冲突解决方案 [英] Collision resolution in Java HashMap

查看:162
本文介绍了Java HashMap中的冲突解决方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HashMap 使用 put 方法将K / V对插入 / code>。
可以说我已经使用了 put 方法,现在 HashMap< Integer,Integer> code> key
为10并且 value 为17

如果我在这个 HashMap 中插入10,20,它只是用相同的键10替换了前一个条目,因为碰撞原因。



如果密钥碰撞 HashMap 用新的K / V对替换旧的K / V对。

所以我的问题是 HashMap 何时使用Chaining碰撞解析技术?



为什么它没有形成一个 linkedlist ,其中键为10,值为17,20?

解决方案

当您插入(10,17)然后(10,20),技术上没有涉及碰撞。你只是用给定键 10 的新值替换旧值(因为在这两种情况下,10等于10,并且10的哈希码始终10)。

当多个键散列到同一个存储桶时发生碰撞。在这种情况下,您需要确保您可以区分这些键。链接冲突解决方案是用于这种技术的技术之一。

例如,假设两个字符串abra ka dabrawave my wand产生散列码 100 200 分别。假设总数组大小为10,那么它们最终会在同一个存储桶中( 100%10 200%10 )。 Chaining可确保无论何时执行 map.get(abra ka dabra); ,您最终都会得到与该关键字相关的正确值。对于Java中的哈希映射,这是通过使用 equals 方法完成的。


Java HashMap uses put method to insert the K/V pair in HashMap. Lets say I have used put method and now HashMap<Integer, Integer> has one entry with key as 10 and value as 17.

If I insert 10,20 in this HashMap it simply replaces the the previous entry with this entry due to collision because of same key 10.

If the key collides HashMap replaces the old K/V pair with the new K/V pair.

So my question is when does the HashMap use Chaining collision resolution technique?

Why it did not form a linkedlist with key as 10 and value as 17,20?

解决方案

When you insert the pair (10, 17) and then (10, 20), there is technically no collision involved. You are just replacing the old value with the new value for a given key 10 (since in both the cases, 10 is equal to 10 and also the hash code for 10 is always 10).

Collision happens when multiple keys hash to the same bucket. In that case, you need to make sure that you can distinguish between those keys. Chaining collision resolution is one of those techniques which is used for this.

As as example, let's suppose that two strings "abra ka dabra" and "wave my wand" yield hash codes 100 and 200 respectively. Assuming the total array size is 10, both of them end up in the same bucket (100 % 10 and 200 % 10). Chaining ensures that whenever you do map.get( "abra ka dabra" );, you end up with the correct value associated with the key. In the case of hash map in Java, this is done by using the equals method.

这篇关于Java HashMap中的冲突解决方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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