gpt4 book ai didi

java - 哈希码和排除字段

转载 作者:行者123 更新时间:2023-11-30 06:06:37 24 4
gpt4 key购买 nike

根据 Bloch 关于 hashCode 的建议:

You may ignore any field whose value can be computed from fields included in the computation

我不明白这个。有人可以举一个真实的例子吗?我假设任何可以从其他字段生成字段的类出于性能原因只会将其存储在另一个变量中。但这与哈希码合约有什么关系?

最佳答案

class Example {
final int a;
final int b;
final int c;

Example(int a, int b) { this.a = a; this.b = b; this.c = a + b; }
}

在此处的 hashCode 计算中包含 c 是没有意义的:ab 的任何实例相等也将有 cs 相等。

Objects.hash(this.a, this.b, this.c) == Objects.hash(that.a, that.b, that.c)
<=>
Objects.hash(this.a, this.b) == Objects.hash(that.a, that.b)

因此,您所做的只是通过包含 c 来“扰乱”哈希码,即使其成为不同的值,但不是以有意义的方式。


String 中的一个实际例子:String 有一个字段,hash,它存储哈希码的值,以避免重复计算(source):

public int hashCode() {
int h = hash; // <-- hash is a member variable.
if (h == 0 && value.length > 0) {
char val[] = value;

for (int i = 0; i < value.length; i++) {
h = 31 * h + val[i];
}
hash = h;
}
return h;
}

也许很明显,这个不能算在哈希码计算中!但它可以从类中的其他字段派生。

关于java - 哈希码和排除字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43678294/

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