8

我有一个不可变的对象,例如笛卡尔空间中的一个节点。该类是不可变的,所以我缓存了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基于 来检查相等性是否正确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;
}

这通过了我写的关于属性和它们的交互的所有单元测试equals()hashCode()但也许我缺少一些东西?

注意: GuavaObjects.hashCode()Objects.equal()是否对各自的方法有帮助。

4

2 回答 2

17

没有; 那是行不通的。

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

于 2012-04-18T00:24:40.857 回答
2

不是,但..

我想您可以检查哈希码以查看对象是否不相等并在那里获得一些性能:

public boolean equals(final Object obj) {
   if (this == obj) { return true; }
   if (!(obj instanceof Node)) { return false; }
   final Node other = (Node) obj;

   if (this.hashCode != other.hashCode) {
      return false; // If hashcodes differ, we're sure the objects are not equal
   }
   // remainder of the actual equals implementation
}

当然,这只会在您的大多数比较结果为假的情况下提高性能。在对象相等的情况下,这将带来性能损失。在您的示例中(仅比较三个值),我不建议这样做。

于 2012-09-05T18:10:02.407 回答