2017-05-22 52 views
-1

我想要FeatureEntryKey用作Map Key,它依賴於兩個字符串。我記得默認情況下,字符串值可以很好地處理平等,所以不需要在這裏自動生成這兩種方法。真的嗎?我是否需要重寫hashCode並使用compareTo方法等於方法?

public class FeatureEntryKey implements Comparable<FeatureEntryKey> { 

    private String my_key; 
    private String my_pos; 

    public FeatureEntryKey(String key, String pos) { 
     my_key = key; 
     my_pos = pos; 

    } 

    String getKey() { 
     return my_key; 
    } 

    String getPos() { 
     return my_pos; 
    } 

    @Override 
    public int compareTo(FeatureEntryKey entryKey) { 
     int key = my_key.compareTo(entryKey.my_key); 

     return key == 0 ? this.my_pos.compareTo(entryKey.my_pos) : key; 
    } 

    /* 
    * (non-Javadoc) 
    * 
    * @see java.lang.Object#hashCode() 
    */ 
    @Override 
    public int hashCode() { 
     final int prime = 31; 
     int result = 1; 
     result = prime * result + ((my_key == null) ? 0 : my_key.hashCode()); 
     result = prime * result + ((my_pos == null) ? 0 : my_pos.hashCode()); 
     return result; 
    } 

    /* 
    * (non-Javadoc) 
    * 
    * @see java.lang.Object#equals(java.lang.Object) 
    */ 
    @Override 
    public boolean equals(Object obj) { 
     if (this == obj) 
      return true; 
     if (obj == null) 
      return false; 
     if (getClass() != obj.getClass()) 
      return false; 
     FeatureEntryKey other = (FeatureEntryKey) obj; 
     if (my_key == null) { 
      if (other.my_key != null) 
       return false; 
     } else if (!my_key.equals(other.my_key)) 
      return false; 
     if (my_pos == null) { 
      if (other.my_pos != null) 
       return false; 
     } else if (!my_pos.equals(other.my_pos)) 
      return false; 
     return true; 
    } 

} 
+0

那究竟是什麼問題? – Mureinik

+1

類別。如果實現'CompareTo',但不覆蓋'equals',則最終可能會出現'a.compareTo(b)== 0'但是'a.equals(b)== false'的情況。這顯然令人困惑。和往常一樣,如果你重寫'equals',你應該重載'hashCode'。 – Michael

回答

1

不; you don't have to,但你真的應該

強烈建議(雖然不要求)自然排序與平等一致。這是因爲排序集合(和排序映射)沒有顯式比較器時,它們與自然排序與equals不一致的元素(或鍵)一起使用時表現得「奇怪」。特別是,這樣的有序集合(或有序映射)違反了集合(或映射)的一般契約,它是用等價方法定義的。

但是,這與String是否可以很好地處理平等無關。那完全是與你實施Comparable的事實有關;在執行Comparable時,您不會默認覆蓋equalshashCode

如果您計劃在一個集合中使用它,其中平等或哈希是一個因素,那麼您會想要重寫這些,以確保您獲得的行爲是您期望的行爲。

+0

所以我最好在這種情況下刪除euqals和hashcode,對吧? – user697911

+0

我沒有看到一個理由。他們似乎沒有被打破,並且讓他們到位*在處理藏品時是個好主意。 – Makoto

+0

從你看到的是,我的compareTo實現是否與生成的equals和hashCode一致? – user697911

相關問題