簡體   English   中英

正確實現哈希碼/等號

[英]Correct implementation of hashcode/equals

我有一堂課

class Pair<T>{
    private T data;
    private T alternative;
}

如果兩個對對象相等

this.data.equals(that.data) && this.alternative.equals(that.alternative) || 
this.data.equals(that.alternative) && this.alternative.equals(that.data)

我在正確實現hashCode()部分方面遇到困難。 任何建議,將不勝感激

您應該使用數據中的hashCode和類似的替代方法:

  return this.data.hashCode() + this.alterative.hashCode();

盡管這不是最佳方法,但是就像您更改數據或替代方法一樣,它們的哈希碼也會更改。 仔細考慮一下,看看您是否真的需要將此類用作映射中的鍵,如果不是,則最好使用Long或String。

這應該可以解決問題:

  @Override
  public int hashCode() {
    return data.hashCode() * alternative.hashCode();
  }

由於要將兩個字段都包含在等號中,因此需要將兩個字段都包含在hashCode方法中。 如果不相等的對象最終具有相同的哈希碼是正確的,但是根據您的方案,相等的對象將始終使用此方法最終具有相同的哈希碼。

參考java doc,hashCode的一般約定是(從java doc復制):

 - Whenever it is invoked on the same object more than once during an
   execution of a Java application, the hashCode method must
   consistently return the same integer, provided no information used in
   equals comparisons on the object is modified. This integer need not
   remain consistent from one execution of an application to another
   execution of the same application.



 - If two objects are equal according to the equals(Object) method, then
   calling the hashCode method on each of the two objects must produce
   the same integer result.



 - It is not required that if two objects are unequal according to the
   equals(java.lang.Object) method, then calling the hashCode method on
   each of the two objects must produce distinct integer results.
   However, the programmer should be aware that producing distinct
   integer results for unequal objects may improve the performance of
   hashtables.

因此,從實現等式開始,數據和替代項都是可切換的。 因此,如果切換data.hashCode()和Alternative.hashCode()的位置,則需要確保在hashCode實現中返回相同的值。 如果不確定,則只返回一個const值,例如1(但是當您嘗試將對象放入Map中時,可能會導致性能問題)。

暫無
暫無

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

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