Java:只检查不可变对象的equals()中的hashCode

Ale*_*kis 7 java equals hashcode immutability guava

我有一个不可变对象,例如笛卡尔空间中的一个节点.该类是不可变的,所以我缓存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;
}
Run Code Online (Sandbox Code Playgroud)

由于它hashCode是唯一的并且依赖于类的所有字段而且类是不可变的,所以仅Node基于hashCode?检查相等性是否正确?

@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;
}
Run Code Online (Sandbox Code Playgroud)

这通过我已经写了约的性质所有单元测试equals(),并hashCode()和它们之间的相互作用,但也许有我丢失的东西?

注:Objects.hashCode()Objects.equal()是番石榴类各自的方法有用.

SLa*_*aks 17

不; 这是行不通的.

您有2 32个可能的哈希码和2 192个可能的值.