簡體   English   中英

Java:只檢查不可變對象的equals()中的hashCode

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

我有一個不可變對象,例如笛卡爾空間中的一個節點。 該類是不可變的,因此我將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是唯一的並且依賴於類的所有字段並且該類是不可變的,因此僅基於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()是對各自方法有幫助的番石榴類。

不; 這是行不通的。

您有2 32個可能的哈希碼和2 192個可能的值。

不是,但..

我想你可以檢查哈希碼,看看對象是否不相等,並在那里獲得一些性能:

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
}

當然,這只會在大多數比較產生錯誤的情況下提高性能。 在對象相同的情況下,這將帶來性能損失。 在您的示例中(僅比較三個值),我不建議這樣做。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM