2016-10-30 59 views
0

我發現這個類的定義:hashcode()和compareTo()如何相關?

class TwoTuple28<A,B> implements Comparable { 
    // ... 
    public int hashCode() { 
    int result = 17; 
    result = result * 37 + first.hashCode(); 
    result = result * 37 + second.hashCode(); 
    return result; 
    } 
    public int compareTo(Object o) { 
    if(!(o instanceof TwoTuple28)) throw new ClassCastException(); 
    TwoTuple28 t = (TwoTuple28)o; 
    return (this.hashCode() - t.hashCode() < 0) ? -1 : 
    ((this.hashCode() - t.hashCode() > 0 ? 1 : 0)); 
} 

能否請你解釋一下我,爲什麼開發者使用的hashCode()到的compareTo()?他們有什麼關係?這不是一個錯誤的方式?

+2

他們沒有關係。這是做錯的方法。 – 4castle

+0

我認爲你找到的代碼非常可怕。 – GhostCat

回答

1

總之,這是一個非常糟糕的主意。它有點作品,但會以很容易在測試中遺漏的方式失敗。

比較的目的是說當一個對象更高,更低或等於另一個時。當兩個對象相等時,它們被認爲是ConcurrentSkipListMap,TreeMap和TreeSet的重複對象,這意味着在這種情況下具有相同hashCode的兩個對象將被認爲是重複的並被忽略。兩個對象具有相同的hashCode的可能性有多大?如果您擁有數以萬計的集合,那麼即使使用比以上更好的hashCode,您也很可能會有重複。

當碰撞時,BTW,HashMap和HashSet現在使用compareTo,即使在這些集合中,compareTo也可能意味着鍵/元素消失。

實現此方法的安全方法是假定第一個和第二個字段爲Comparable,否則您無法比較它們。


在一個相關的說明,爲你一個難題。

編寫一個程序來打印有hashCode()0的字符串。您應該能夠在不到十秒的時間內生成數千個數據。