我發現這個類的定義: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()?他們有什麼關係?這不是一個錯誤的方式?
他們沒有關係。這是做錯的方法。 – 4castle
我認爲你找到的代碼非常可怕。 – GhostCat