java HashMap 冲突 [英] java HashMap collision

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

问题描述

我正在阅读有关 hashmap 的工作原理.我正在阅读如果两个不同的对象具有相同的哈希码会发生什么".

I was reading about how hashmap works. I was reading through the "What will happen if two different objects have same hashcode".

如果两个对象具有相同的哈希码,则两者都将存储在 LinkedList 但据我所知,如果两个哈希码然后前一个哈希码将被新的覆盖(如果我错了,请纠正我).

According to it if two objects has same hashcode both will be stored in LinkedList but as far as I know if two hashcode then previous one will get overridden with new one(correct me if I am wrong).

有人可以详细说明一下 hashmap 如何在内部使用对象作为键,如果两个对象具有相同的 hashcode 会发生什么,以及如何使用 get() 获取这两个对象?

Can someone please put more light on how hashmap use object as key internally and what will happen if two objects has same hashcode and how both objects will be fetched with get()?

推荐答案

不,第一个不会因为第二个具有相同的 hashCode 而被覆盖.

No, the first one isn't overridden just because the second one has the same hashCode.

只有当它也相等时才会被覆盖(如 equals 所说).如果没有,这两个值都将保存在链表中.

It will be overridden only if it is also equal (as said by equals). If not, both values will be kept in the linked list.

当获取一个键时,所有具有相同 hashCode 的节点将与提供的键进行比较,直到一个相等,然后它的值将被返回(使用 equals 方法).

When fetching a key, all nodes with the same hashCode will be compared to the provided key until one is equal then its value will be returned (using the equals method).

如果地图中没有相同的键,你会得到 null.

If no key in the map is equal, you'll get null.

如果许多对象具有相同的 hashCode(或者更准确地说是相同的 hashCode 以内部 Entry[] 表的大小为模),那么您遇到的唯一问题是链接列表将始终被读取,这更慢(并且破坏了任何哈希表的目的).这就是为什么在设计 hashcode 方法以确保生成的整数分布良好时很重要的原因.

The only problem you have if many objects have the same hashCode (or more precisely the same hashCode modulo the size of the internal Entry[] table) is that the linked list will always be read, which is slower (and defeats the purpose of any hash table). That's why it's important when designing a hashcode method to ensure the generated integers are well distributed.

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

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