比较方法在排序时违反了它的一般契约

Comparison method violates its general contract when sorting

我不断收到:比较方法违反了它的一般合同!当我调用 Arrays.sort(ScreenItems) 时,下面的比较函数出现异常
我的一个假设是下面的 ParseInt 正在为左侧对象而不是右侧对象抛出异常
难道是这样吗?

public int compare(Object o1, Object o2) {
    if (o2 == null || o1 == null)
        return 0;

    if (!(o1 instanceof ScreenItem) || !(o2 instanceof ScreenItem))
        return 0;

    ScreenItem item1 = (ScreenItem) o1;
    ScreenItem item2 = (ScreenItem) o2;

    String subSystem1 = item1.getSubSystem();
    String subSystem2 = item2.getSubSystem();

    if(subSystem1.equals(subSystem2)) {
        return 0;
    } else if(subSystem1.startsWith(subSystem2)) {
        return 1;
    } else if (subSystem2.startsWith(subSystem1)) {
        return -1;
    }

    String order1 = item1.getOrder();
    String order2 = item2.getOrder();

    if (order1 == null || order2 == null){
        String name1 = item1.getName();
        String name2 = item2.getName();

        if(name1 == null || name2 == null)
            return 0;

        return name1.compareToIgnoreCase(name2);
    }

    try {
        return Integer.parseInt(order1) - Integer.parseInt(order2);
    } catch (Exception ex) {
        return 0;
    }
}

这是我认为需要进行的那种改变的一个例子。正如@CommuSoft 在评论中指出的那样,目前 nullo1o2 的处理破坏了传递性。

我会替换:

if (o2 == null || o1 == null)
    return 0;

与:

if (o2 == null && o1 == null)
    return 0;
if (o1 == null)
    return -1;
if (o2 == null)
    return 1;

这将 null 视为等于其自身,但小于所有非空引用。当然,您也可以选择将 null 视为大于所有非空引用,只要您保持一致即可。如果有任何两个非空引用,您 return 一个非零值,则将其视为等于所有内容(如在当前代码中所做的那样)是不一致的。

更一般地说,我建议为排序编写一组规则,确保它们符合 Comparator 合同,然后编写代码和测试以匹配这些规则。