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); } }); }
p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Monaco; color: #ff2600 }
span.s1 { text-decoration: underline; color: #0433ff }
span.Apple-tab-span { white-space: pre }
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
p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Monaco }