gpt4 book ai didi

java - 哈希码和等于

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:37:59 25 4
gpt4 key购买 nike

equalshashCode 方法必须一致,也就是说当两个对象根据equals 方法相等时他们的hashCode 方法应该返回相同的哈希值。

如果我们不重写 hashCode() 方法,Java 将返回一个唯一的哈希码。

class HashValue {

int x;

public boolean equals(Object oo) {
// if(oo instanceof Hashvalue) uncommenting ths gives error.dunno why?
// :|
HashValue hh = (HashValue) oo;

if (this.x == hh.x)
return true;
else
return false;
}

HashValue() {
x = 11;
}

}

class Hashing {
public static void main(String args[]) {
HashValue hv = new HashValue();
HashValue hv2 = new HashValue();

System.out.println(hv.hashCode());
System.out.println(hv2.hashCode());

if (hv.equals(hv2))
System.out.println("EQUAL");
else
System.out.println("NOT EQUAL");
}
}

为什么取消注释该行会导致编译错误?

如果对象具有不相等的哈希码,为什么它们显示为相等,即使默认哈希码不同?

最佳答案

相等性仅由方法 equals() 确定。方法 hashCode() 用于其他情况,例如 Map 或 Set。它有点像实际调用 equals 之前的先决条件或提示(为了提高效率)。所以假设如果 2 个对象相等(即 equals() 返回 true),那么它们的 hashCodes() 必须返回相同的值。

所以在您的代码中,只要您覆盖的 equals() 返回 true,无论 hashCode() 做什么,2 个对象都是相等的。比较相等性时根本不调用 hashCode()。

This question有关于 equals() 和 hashCode() 之间关系的更深入的信息。

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

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