java HashMap冲突 [英] java HashMap collision

查看:98
本文介绍了java 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).

有人可以进一步说明哈希图如何在内部使用对象作为键,以及如果两个对象具有相同的哈希码会发生什么,以及如何使用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(或更精确地说,是内部Entry[] table的大小的相同hashCode),则您唯一的问题是,链表将始终被读取,这会更慢(并破坏了目的)任何哈希表).这就是为什么在设计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天全站免登陆