我已经为我的类定义了hashCode()
,其中包含了很长的属性列表。
按照契约,我还需要实现equals()方法,但是是否可能只需在里面比较hashCode()
来避免编写大量额外的代码?这样做是否存在任何危险呢?
例如:
@Override
public int hashCode()
{
return new HashCodeBuilder(17, 37)
.append(field1)
.append(field2)
// etc.
// ...
}
@Override
public boolean equals(Object that) {
// Quick special cases
if (that == null) {
return false;
}
if (this == that) {
return true;
}
// Now consider all main cases via hashCode()
return (this.hashCode() == that.hashCode());
}
#equals()
,#hashCode()
和#toString()
方法,省去了手动编写的烦恼。"AutoValue"。 - Tom