我发现这个类的定义: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