简体   繁体   English

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

[英]Java: Only check hashCode in equals() of immutable object

I have an immutable object, for example a node in the Cartesian space. 我有一个不可变对象,例如笛卡尔空间中的一个节点。 The class is immutable, so I cache the hashCode for very fast hashing. 该类是不可变的,因此我将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;
}

Since the hashCode is unique and dependent on all fields of the class AND the class is Immutable, would it be correct to only check Node equality based on the hashCode ? 由于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;
}

This passes all Unit Tests I have written about the properties of equals() and hashCode() and their interaction, but perhaps there is something I am missing? 这传递了我所写的关于equals()hashCode()属性及其相互作用的所有单元测试,但也许有些东西我不知道了?

Note: Objects.hashCode() and Objects.equal() are Guava classes helpful for the respective methods. 注意: Objects.hashCode()Objects.equal()是对各自方法有帮助的番石榴类。

Nope; 不; that won't work. 这是行不通的。

You have 2 32 possible hashcodes and 2 192 possible values. 您有2 32个可能的哈希码和2 192个可能的值。

No, but.. 不是,但..

I guess you could check the hashcode to see whether objects are not equal and gain some performance there: 我想你可以检查哈希码,看看对象是否不相等,并在那里获得一些性能:

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
}

Of course this will only improve performance in case most of your comparisons yield false. 当然,这只会在大多数比较产生错误的情况下提高性能。 In case of equal objects, this will bring a performance penalty. 在对象相同的情况下,这将带来性能损失。 In your example (comparing just three values), I wouldn't recommend this. 在您的示例中(仅比较三个值),我不建议这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM