[ Error 分析] Comparison method violates its general contract!

Posted 乔桑宁

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[ 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

 

 

以上是关于[ Error 分析] Comparison method violates its general contract!的主要内容,如果未能解决你的问题,请参考以下文章

python --RecursionError: maximum recursion depth exceeded in comparison

在 scikit learn 中准备和可视化分类报告时出现错误“FutureWarning: elementwise comparison failed”

实力踩坑:invalid comparison: java.util.Date and java.lang.String

SE Homework 1 —An Error Impressed Me

An error from other projects which impress me most

如何修复解析错误:Vue 中的 invalid-first-character-of-tag-name.eslint (vue/no-parsing-error)