@Edit:我正在使用这个库http://jqno.nl/equalsverifier/来检查是否正确equals
编写hashCode
。
假设我们有这个类:
final class Why {
private final int id;
private final String name;
Why(final int id, final String name) {
this.id = id;
this.name = name;
}
@Override
public boolean equals(final Object o) {
if (this == o) return true;
if (!(o instanceof Why)) return false;
final Why why = (Why) o;
if (id != why.id) return false;
return name != null ? name.equals(why.name) : why.name == null;
}
@Override
public int hashCode() {
return id;
}
}
在hashCode
我只在id
现场中继,因为这会给我很好的非冲突哈希。值得注意的是这种hash
方法符合所有规则equals-hashCode
。我不想用求和哈希做一些花哨的技巧,即:
@Override
public int hashCode() {
int result = id;
result = 31 * result + (name != null ? name.hashCode() : 0);
return result;
}
那么你能解释一下为什么EqualsVerifer
默认需要使用equals
方法中的所有字段hashCode
吗?
java.lang.AssertionError: Significant fields: equals relies on subValue, but hashCode does not.