Caused by: java.lang.IllegalArgumentException: Comparison method violates its general contract!
Caused by: java.lang.IllegalArgumentException: Comparison method violates its general contract!
酷游博客

Caused by: java.lang.IllegalArgumentException: Comparison method violates its general contract!

酷游
1月22日发布 /正在检测是否收录...

Caused by: java.lang.IllegalArgumentException: Comparison method violates its general contract!

问题

导致该异常的原因有以下两点构成:1.使用了jdk7 2.使用了比较器,并且比较器违反了比较规则
以下是关于比较器不兼容的声明:

Area: API: Utilities  
Synopsis: Updated sort behavior for Arrays and Collections may throw an IllegalArgumentException  
Description: The sorting algorithm used by java.util.Arrays.sort and (indirectly) by java.util.Collections.sort has been replaced.   
The new sort implementation may throw an IllegalArgumentException if it detects a Comparable that violates the Comparable contract.   
The previous implementation silently ignored such a situation.  
If the previous behavior is desired, you can use the new system property, java.util.Arrays.useLegacyMergeSort,   
to restore previous mergesort behavior.  
Nature of Incompatibility: behavioral  
RFE: 6804124  

描述的意思是说,java.util.Arrays.sort(java.util.Collections.sort调用的也是此方法)方法中的排序算法在JDK7中已经被替换了。如果违法了比较的约束新的排序算法也许会抛出llegalArgumentException异常。JDK6中的实现则忽略了这种情况。那么比较的约束是什么呢?看这里,大体如下:

sgn(compare(x, y)) == -sgn(compare(y, x))
((compare(x, y)>0) && (compare(y, z)>0)) implies compare(x, z)>0
compare(x, y)==0 implies that sgn(compare(x, z))==sgn(compare(y, z)) for all z

当x == y时,sgn(compare(x, y)) = -1,-sgn(compare(y, x)) = 1,这违背了sgn(compare(x, y)) == -sgn(compare(y, x))约束,所以在JDK7中抛出了本文标题的异常。

解决方式

1.JVM加入如下参数-Djava.util.Arrays.useLegacyMergeSort=true,表示使用JDK6的排序算法

2.按照规定的比较规则进行值的返回,a==b 返回 0,ab 返回 1

© 版权声明
THE END
喜欢就支持一下吧
点赞 0 分享 赞赏
评论
当前页面的评论已关闭
易航博客
SSL