Java 为什么这种比较法违反了它的总合同?

Java 为什么这种比较法违反了它的总合同?,java,exception,compare,Java,Exception,Compare,我正在使用一个特殊的比较器,根据配对的第二部分对配对列表进行排序: Collections.sort(ans, new Comparator<Pair<Component, Double>>() { public int compare(Pair<Component, Double> l, Pair<Component, Double> r) { if (r.second - l.second <

我正在使用一个特殊的比较器,根据配对的第二部分对配对列表进行排序:

Collections.sort(ans, new Comparator<Pair<Component, Double>>()
    {
      public int compare(Pair<Component, Double> l, Pair<Component, Double> r)
      {
        if (r.second - l.second < 0) return  -1;
        else if(r.second==l.second) return 0;
        else return 1;
      }
    });
Collections.sort(ans,新的比较器()
{
公共整数比较(对l,对r)
{
如果(r.second-l.second<0)返回-1;
else如果(r.second==l.second)返回0;
否则返回1;
}
});
比较方法似乎是可传递的(aa它等于它本身。什么可能导致异常?

有些边缘情况您没有考虑,也不应该考虑,因为JDK已经提供了一种完全兼容的方法,为了完整起见,我在这里介绍了这种方法:

public static int compare(double d1, double d2) {
    if (d1 < d2)
        return -1;           // Neither val is NaN, thisVal is smaller
    if (d1 > d2)
        return 1;            // Neither val is NaN, thisVal is larger

    // Cannot use doubleToRawLongBits because of possibility of NaNs.
    long thisBits    = Double.doubleToLongBits(d1);
    long anotherBits = Double.doubleToLongBits(d2);

    return (thisBits == anotherBits ?  0 : // Values are equal
            (thisBits < anotherBits ? -1 : // (-0.0, 0.0) or (!NaN, NaN)
             1));                          // (0.0, -0.0) or (NaN, !NaN)
}
公共静态整数比较(双d1,双d2){
如果(d1d2)
return 1;//两个val都不是NaN,thisVal更大
//由于可能出现NAN,无法使用doubleToRawLongBits。
长位=Double.Double到长位(d1);
长另一位=双。双到长位(d2);
返回(thisBits==其他位?0://值相等
(此位<其他位?-1://(-0.0,0.0)或(!NaN,NaN)
1) );/(0.0,-0.0)或(NaN,!NaN)
}

r.second-l.second<0中可能出现的溢出遵循最佳实践,始终使用
Double.compare(Double,Double)
(以及所有其他原语类型的等价项)。+1因此,为了完成答案,Marko建议您只需执行
返回Double.compare(l.second,r.second)而不是您已有的代码。