如果两个不同的对象具有相同的哈希码会发生什么? [英] What happens if two different objects have the same hashcode?

查看:158
本文介绍了如果两个不同的对象具有相同的哈希码会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的理解是两个不相等的对象可以有相同的哈希码。如何在HashMap java中添加或检索时处理这些数据?

解决方案

它们只会被添加到同一个存储桶中, code> equals()将用于区分它们。
每个桶可以包含具有相同哈希代码的对象列表。

理论上,您可以返回与给定对象相同的整数作为哈希代码类,但这意味着你将散列散列图的所有性能优点,实际上将把对象存储在列表中。


It is my understanding that two unequal objects can have the same hashcode. How would this be handled when adding or retrieving from a HashMap java?

解决方案

They will just be added to the same bucket and equals() will be used to distinguish them. Each bucket can contain a list of objects with the same hash code.

In theory you can return the same integer as a hash code for any object of given class, but that would mean that you loose all performance benefits of the hash map and, in effect, will store objects in a list.

这篇关于如果两个不同的对象具有相同的哈希码会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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