首页 > 代码库 > Comparison method violates its general contract

Comparison method violates its general contract

 

生产环境出现的错误排查,错误log如下

java.lang.IllegalArgumentException: Comparison method violates its general contract!	at java.util.TimSort.mergeLo(TimSort.java:747) ~[na:1.7.0_40]	at java.util.TimSort.mergeAt(TimSort.java:483) ~[na:1.7.0_40]	at java.util.TimSort.mergeCollapse(TimSort.java:408) ~[na:1.7.0_40]	at java.util.TimSort.sort(TimSort.java:214) ~[na:1.7.0_40]	at java.util.TimSort.sort(TimSort.java:173) ~[na:1.7.0_40]	at java.util.Arrays.sort(Arrays.java:659) ~[na:1.7.0_40]	at java.util.Collections.sort(Collections.java:217) ~[na:1.7.0_40]

 整个问题在生产环境上间断性出现,在本地开发环境是好的,上网搜了下这个错误,发现遇到的人还不少。具体的原因是因为jdk7的timesort新排序算法导致,具体可以参考这篇博文:

http://www.lifebackup.cn/timsort-java7.html

总结如下:比较器的比较逻辑必须正确,且需要放回相等的情况,即0;同时需要注意的是对于引用类型的比较需要转化成简单类型进行比较

 

Comparison method violates its general contract