[英]Is this a good implementation of hashCode()?
我有一个将在HashSet
使用的class
。 它只包含两个成员,两者都是相同类型的接口。 这就是它的样子:
class MyClass{
MyInterface a;
MyInterface b;
public int hashCode(){
return a.hashCode() + b.hashCode();
}
public boolean equals(Object obj){
if(!(obj instanceof MyClass)
return false;
MyClass other (MyClass) obj;
return (this.a == other.a && this.b == other.b) || (this.a == other.b && this.b == other.a);
}
}
如您所见,如果MyClass
两个实例包含相同的两个MyInterface
实例,则它们是“相等的”。
现在,我在想,对于hashCode()
,我可以添加其成员的默认哈希码。 这够好吗? 如果没有,对于这种情况, hashCode()
的正确实现是什么?
是的,这很好。 它相当于为两元素集实现Set.hashCode()
。
我会说不。 这不意味着MyClass
这两个实例将散列为相同的值:
MyClass {
a.hashCode = 2;
b.hashCode = 3;
}
和
MyClass {
a.hashCode = 1;
b.hashCode = 4;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.