我有一个不可变对象(immutable对象),例如笛卡尔空间中的一个节点。该类是不可变的,因此我缓存了 hashCode
以实现非常快速的散列。
private final int hashCode;
private final double x, y, z;
public Node(final double x, final double y, final double z)
{
this.x = x;
this.y = y;
this.z = z;
this.hashCode = Objects.hashCode(this.x, this.y, this.z);
}
@Override
public boolean equals(final Object obj)
{
if (this == obj) { return true; }
if (obj == null) { return false; }
if (!(obj instanceof Node)) { return false; }
final Node other = (Node) obj;
return Objects.equal(this.x, other.x) && Objects.equal(this.y, other.y) && Objects.equal(this.z, other.z);
}
@Override
public int hashCode()
{
return this.hashCode;
}
由于 hashCode
是唯一的并且依赖于类的所有字段并且该类是不可变的,是否仅根据 检查
?Node
相等性是否正确>哈希码
@Override
public boolean equals(final Object obj)
{
if (this == obj) { return true; }
if (obj == null) { return false; }
if (!(obj instanceof Node)) { return false; }
final Node other = (Node) obj;
return this.hashCode == other.hashCode;
}
这通过了我写的关于 equals()
和 hashCode()
的属性及其交互的所有单元测试,但也许我遗漏了什么?
注意:Objects.hashCode()
和 Objects.equal()
是有助于各自方法的 Guava 类。
最佳答案
没有;那是行不通的。
您有 232 个可能的哈希码和 2192 个可能的值。
关于Java:只检查不可变对象(immutable对象)的equals()中的hashCode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10201083/