【发布时间】:2015-06-11 19:17:27
【问题描述】:
我有一个class,将在HashSet 中使用。它只包含两个成员,并且都是相同类型的接口。这是它的样子:
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() 的正确实现是什么?
【问题讨论】:
-
a和b的hashcode是怎么定义的?
-
这将提供不相等的哈希码分布:
Integer.MaxValue / 2周围的元素与极端元素相比将不成比例地表示,从而导致更多的哈希冲突。 -
你也可以使用:
return Objects.hash(a, b); -
@assylias 不,这将为相等的对象提供两个不同的哈希码,因为 [a, b] 等于 [b, a]
-
@assylias OP 似乎需要一些与订单无关的东西,
Objects.hash不是
标签: java equals implementation hashcode