java SortBy崩溃违反了合同
嘿,伙计们,我有这段代码要根据持续时间进行比较,但我一直得到这个错误:
Fatal Exception: java.lang.IllegalArgumentException Comparison method violates its general contract!
这是我的密码:
Collections.sort(list, new Comparator<MyProduct>() {
@Override
public int compare(MyProduct lhs, MyProduct rhs) {
Integer lDuration = (lhs != null ? lhs.getDuration() :0);
Integer rDuration = (rhs != null ? rhs.getDuration() :0);
return lDuration.compareTo(rDuration);
}
});
# 1 楼答案
您违反了consistency with equals的要求:
你是说null等于一个持续时间为零的实例,而事实并非如此,因为
zeroDuration.equals(null)
是false(或者至少是it should be),并且null.equals(zeroDuration)
会导致异常你应该决定要么把所有空元素放在第一位,要么把所有空元素放在最后