Java HashMap 中的冲突解决

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

问题描述

Java HashMap 使用put 方法在HashMap 中插入K/V 对.假设我使用了 put 方法,现在 HashMap 有一个条目,其中 key 为 10,value 为 17.

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.

如果我在这个 HashMap 中插入 10,20,由于相同的键 10 发生冲突,它只是用这个条目替换上一个条目.

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.

如果键冲突 HashMap 用新的 K/V 对替换旧的 K/V 对.

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

所以我的问题是 HashMap 什么时候使用链式冲突解决技术?

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

为什么它没有形成一个key为10,value为17,20的linkedlist?

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

推荐答案

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

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 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.

例如,假设两个字符串 "abra ka dabra""wave my wand" 产生哈希码 100200.假设总数组大小为 10,它们最终都在同一个存储桶中(100 % 10200 % 10).链接确保无论何时执行 map.get("abra ka dabra" );,最终都会得到与键关联的正确值.对于 Java 中的哈希映射,这是通过使用 equals 方法完成的.

As an 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 中的冲突解决的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

How can create a producer using Spring Cloud Kafka Stream 3.1(如何使用Spring Cloud Kafka Stream 3.1创建制片人)
Insert a position in a linked list Java(在链接列表中插入位置Java)
Did I write this constructor properly?(我是否正确地编写了这个构造函数?)
Head value set to null but tail value still gets displayed(Head值设置为空,但仍显示Tail值)
printing nodes from a singly-linked list(打印单链接列表中的节点)
Control namespace prefixes in web services?(控制Web服务中的命名空间前缀?)