zoukankan      html  css  js  c++  java
  • [ Error 分析] Comparison method violates its general contract!

          public static void main(String[] args) {        
    List
    <Long> ret = new ArrayList<>(); int n = 103000; for(int i=0;i<n;i++){ ret.add(new Random().nextLong()); } Collections.sort( ret , new Comparator<Long>(){ @Override public int compare(Long o1, Long o2) { return (int) (o2-o1); } }); }

    Exception in thread "main" java.lang.IllegalArgumentException: Comparison method violates its general contract!

    at java.util.TimSort.mergeLo(TimSort.java:777)

    at java.util.TimSort.mergeAt(TimSort.java:514)

    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:1454)

    at java.util.Collections.sort(Collections.java:175)

     

    一直以为没有什么问题,大于,小于,等于情况都考虑了。 原来原因是:integer overflow,看下面的例子就明白了。负数-正数=正数

    o2:-273192312377492627

    o1:3368764997970232313

    o2-o1:1167472500

    所以,这个compare里面定义的方法不符合compare的约束(传递性,对称性,反对称性)

    PS:https://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html#compare(T,%20T)

    http://svn.python.org/projects/python/trunk/Objects/listsort.txt

     

  • 相关阅读:
    用导数解决逗逼初三数学二次函数图像题
    NOIP 2014 pj & tg
    BZOJ 1004
    双参数Bellman-ford带队列优化类似于背包问题的递推
    emu1
    無題
    15 day 1代碼
    javascript quine
    线段树的总结
    Watering the Fields(irrigation)
  • 原文地址:https://www.cnblogs.com/hongdanning/p/8086066.html
Copyright © 2011-2022 走看看