Java 使用 Math.abs(diff) 排序时出现意外的 IllegalArgumentException

Java unexpected IllegalArgumentException in sorting with Math.abs(diff)

在对双打列表进行排序时,我有一些意料之外的行为。我的目标是对双打列表进行排序,但是当两个双打彼此靠近时,我不关心它们的顺序(实际上,我使用 Entry<> 和 Double 作为值,当两个 Double 值很接近,我按其他排序。

这是一个将抛出 IllegalArgumentException 的示例:

public static void main(String[] args) {
    final float probabilitySortMargin = 0.2f;
    Comparator<Double> comp = new Comparator<Double>() {
        @Override
        public int compare(Double o1, Double o2) {
            // sort on probability first
            double diff = Math.abs(o1 - o2);
            if(diff > probabilitySortMargin)
                // difference is more than desired range, sort descending
                return Double.compare(o2 , o1);
            return 0;
        }
    };

    ArrayList<Double> vals = new ArrayList<>();
    Random r = new Random(0);
    for(int i=0;i<1000;i++)
        vals.add(r.nextDouble());

    for(int i=0;i<vals.size();i++)
        for(int j=0;j<vals.size();j++)
            if(comp.compare(vals.get(i), vals.get(j)) != -1 * comp.compare(vals.get(j), vals.get(i)))
                System.out.println("Comparison failed");

    Collections.sort(vals, comp);
}

这导致

Exception in thread "main" java.lang.IllegalArgumentException: Comparison method violates its general contract!
    at java.util.TimSort.mergeHi(TimSort.java:899)
    at java.util.TimSort.mergeAt(TimSort.java:516)
    at java.util.TimSort.mergeCollapse(TimSort.java:441)
    at java.util.TimSort.sort(TimSort.java:245)
    at java.util.Arrays.sort(Arrays.java:1512)
    at java.util.ArrayList.sort(ArrayList.java:1462)
    at java.util.Collections.sort(Collections.java:175)
    at some.package.Sample.main(Sample.java:10)

为什么会这样?更奇怪的是,错误消息 "Comparison failed" 是 NOT 打印的。

您的 compare 方法确实违反了 Comparator 接口的约定。

the implementor must ensure that compare(x, y)==0implies that sgn(compare(x, z))==sgn(compare(y, z)) for all z.

compare(0.1,0.2) == 0, but sgn(compare(0.1,0.35)) != sgn(compare (0.2,0.35))

"Comparison failed" 永远不会打印,因为您的方法没有违反 sgn(compare(x, y)) ==-sgn(compare(y, x)) 要求。