Comparison method violates its general contract
程序员文章站
2024-02-22 23:48:16
...
Collections.sort(list, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
// return o1 > o2 ? 1 : -1;
return o1.compareTo(o2);// 正确的方式
}
});
经过搜索得知,在JDK7以后,实现Comparable接口后,要满足一下三个特性:
1) 自反性:x,y 的比较结果和 y,x 的比较结果相反。
2) 传递性:x>y,y>z,则 x>z。
3) 对称性:x=y,则 x,z 比较结果和 y,z 比较结果相同。
collections.sort()方法异常,原因:
1. 比较对象存在null等。
if (this.xxx == null && o.xxx == null) {
return 0;
}
if (this.xxx == null) {
return 1;
}
if (o.xxx == null) {
return -1;
}
2. 可能为JDK版本不兼容的问题,JDK7及以后可能会异常,因版本更新,未兼容老版本。
解决方法,排序前插入如下:
System.setProperty("java.util.Arrays.useLegacyMergeSort", "true");
参考:
推荐阅读
-
Comparison method violates its general contract
-
Comparison method violates its general contract!
-
Comparison method violates its general contract!
-
Comparison method violates its general contract!
-
Comparison method violates its general contract
-
java中排序报:Comparison method violates its general contract异常的解决
-
java中排序报:Comparison method violates its general contract异常的解决
-
java 排序报:Comparison method violates its general contract异常的解决方法
-
java 排序报:Comparison method violates its general contract异常的解决方法
-
Comparison method violates its general contract!