gpt4 book ai didi

java - 我应该使用什么作为空的哈希码?

转载 作者:行者123 更新时间:2023-11-30 08:18:44 26 4
gpt4 key购买 nike

假设我们有一个简单的类:

public class Foo {

public Integer bar;

}

我们想为它构建一个“好的”hashCode 方法。例如,我所说的“好”是指在“现实生活”情况下哈希码冲突的可能性很小。

在“现实生活”中,对于这样一个类,我合理地期望 Foobar 设置为 null0 。我什至认为这两个可能是最常见的值。

但让我们看一下 Eclipse 生成的内容:

public class Foo {

public Integer bar;

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((bar == null) ? 0 : bar.hashCode());
return result;
}
}

不仅是 Eclipse,似乎使用 0 作为 nullhashCode 是一种正常做法。

但这会为 null0 生成相同的哈希码,不是吗?我假设 null0 可能是最常见的情况 - 这会导致更高的碰撞概率。

所以我的问题来了。 什么是 null 的良好 hashCode 值?

最佳答案

来自 Joshua Bloch 的优秀著作 Effective Java,第 2 版(第 49 页):

If the value of the field is null, return 0 (or some other constant, but 0 is traditional).

因此您可以使用您选择的任何常量,但通常,0 用作null 的哈希码。

在您的情况下,0 经常出现,选择与 0 不同的常量(在您的字段中未显示为有效值的常量)可能确实更好,以避免冲突。

关于java - 我应该使用什么作为空的哈希码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27268795/

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