• [ 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

     

  • 相关阅读:
    20150324--Mysql索引优化-02
    20150324--Mysql索引优化-01
    20150323--memcache-02
    20150323--memcache-01
    轮播效果/cursor
    事件监听和事件概念
    BOM与DOM操作
    for循环语句/命名函数
    数组/控制语句
    数据类型转换/正则表达式
  • 原文地址:https://www.cnblogs.com/hongdanning/p/8086066.html
Copyright © 2020-2023  润新知