报错:java.lang.IllegalArgumentException: Comparison method violates its general contract!
at java.util.TimSort.mergeHi(TimSort.java:899)
at java.util.TimSort.mergeAt(TimSort.java:516)
at java.util.TimSort.mergeCollapse(TimSort.java:439)
at java.util.TimSort.sort(TimSort.java:245)
at java.util.Arrays.sort(Arrays.java:1512)
at java.util.ArrayList.sort(ArrayList.java:1462)
经过搜索得知,在JDK7以后,实现Comparable接口后,要满足一下三个特性:
1) 自反性:x,y 的比较结果和 y,x 的比较结果相反。
2) 传递性:x>y,y>z,则 x>z。
3) 对称性:x=y,则 x,z 比较结果和 y,z 比较结果相同。
我的代码
resp.getOrderVoList().sort((o1, o2) -> {
int closingDate = o2.getClosingDate().compareTo(o1.getClosingDate());
if (closingDate != 0) {
return closingDate;
}
if (Objects.isNull(o1.getOrderCreatedAt()) || Objects.isNull(o2.getOrderCreatedAt())) {
return 0;
}
});
绿色字体违反了对称性
代码修改
resp.getOrderVoList().sort((o1, o2) -> {
int closingDate = o2.getClosingDate().compareTo(o1.getClosingDate());
if (closingDate != 0) {
return closingDate;
}
if (Objects.isNull(o1.getOrderCreatedAt()) || Objects.isNull(o2.getOrderCreatedAt())) {
if (Objects.isNull(o1.getOrderCreatedAt()) && Objects.isNull(o2.getOrderCreatedAt())) {
return 0;
}
if (Objects.isNull(o1.getOrderCreatedAt())) {
return 1;
} else {
// o2.getOrderCreatedAt() is not null
return -1;
}
} else {
return o2.getOrderCreatedAt().compareTo(o1.getOrderCreatedAt());
}
});
问题解决