gpt4 book ai didi

java - Object.hashCode() 返回重复项

转载 作者:行者123 更新时间:2023-12-02 05:29:56 25 4
gpt4 key购买 nike

我有一个生成 String 对象的类:

key = "K:" + this.hashCode();

该类不继承自任何其他类,并且不会重写 hashCode()。我遇到过这样的情况:我得到了重复的键,因此一个对象的两个不同实例返回完全相同的 hashCode()。

这种情况怎么会发生以及可以采取哪些措施来避免这种情况?这个类是我正在使用的 API 的一部分,所以我无法控制它,但是如果有某种方法可以在我创建这个对象的实例时进行等待或其他操作,那么类似的事情就可以工作。

最佳答案

这可能会发生。您可能会为两个不同的对象获得相同的哈希码:

根据 Object.hashCode()文档:

It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.

可以采取什么措施来避免这种情况? 

以下是其他 SO 问题中建议的一些最佳实践:

Hashcode implementation best practice1

Hashcode implementation best practice2

不过,这些只是最佳实践,不能保证避免相同的哈希码。就您而言,我认为您根本不应该依赖哈希码。

关于java - Object.hashCode() 返回重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18518864/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com