有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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) 个答案

  1. # 1 楼答案

    您违反了consistency with equals的要求:

    When we say that the ordering imposed by c on S is consistent with equals, we mean that the quotient for the ordering is the equivalence relation defined by the objects' equals(Object) method(s):

    {(x, y) such that x.equals(y)}
    

    你是说null等于一个持续时间为零的实例,而事实并非如此,因为zeroDuration.equals(null)是false(或者至少是it should be),并且null.equals(zeroDuration)会导致异常

    你应该决定要么把所有空元素放在第一位,要么把所有空元素放在最后