当equals()基于多个独立字段时,hashCode()方法 [英] hashCode() method when equals() is based on multiple independent fields
问题描述
我有一个等级基于2个字段的类,如果其中任何一个相等,那么这种类型的对象被认为是相等的。我如何为这样的equals()编写一个hashCode()函数,以便当equals返回true时hashCode的一般契约保持不变?
i have a class whose equality is based on 2 fields such that if either one is equal then the objects of this type are considered equal. how can i write a hashCode() function for such an equals() so that the general contract of hashCode being equal when equals returns true is preserved?
public class MyClass {
int id;
String name;
public boolean equals(Object o) {
if (!(o instanceof MyClass))
return false;
MyClass other = (MyClass) o;
if (other.id == this.id || other.name == this.name)
return true;
return false;
}
}
我如何为此编写hashCode()函数类?我想避免像这样返回一个常量的简单案例:
how do i write a hashCode() function for this class? and i want to avoid the trivial case here of returning a constant like so:
public int hashCode() {
return 1;
}
推荐答案
我不认为存在非平凡的哈希码。此外,您的等于()
违反了一般合同在API中说明 --- 不可传递:
I don't think a nontrivial hashcode exists. Also, your equals()
violates the general contract as stated in the API --- it is not transitive:
(1,2)
等于(1,3)
(4,3)
等于(1,3)
但是(4,3)
不等于到( 1,2)
。
为了完整起见,我向您呈现< a href =https://stackoverflow.com/questions/479105/hashcode-method-when-equals-is-based-on-multiple-independent-fields#479128> Skeet - Niko 证明=)
For the sake of completeness, I present to you the Skeet-Niko proof =)
声明:哈希码必须是普通的常量函数。
证明:设(a,b)
和(c,d)
是两个具有不同哈希码的对象,即 h(a,b)≠h(c,d)
。考虑对象(a,d)
。根据OP的定义,(a,d)
等于(a,b)
和(a,d)
等于(c,d)
。它来自哈希码合约 h(a,d)= h(a,b)= h(c,d)
;矛盾。
Proof: Let (a,b)
and (c,d)
be two objects with distinct hashcodes, i.e. h(a,b) ≠ h(c,d)
. Consider the object (a,d)
. By the OP's definition, (a,d)
is equal to (a,b)
, and (a,d)
is equal to (c,d)
. It follows from the hashcode contract that h(a,d) = h(a,b) = h(c,d)
; a contradiction.
这篇关于当equals()基于多个独立字段时,hashCode()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!