快捷搜索: 王者荣耀 脱发

排序问题排查Comparison method violates its general contract!

通过List.sort对元素进行排序,测试阶段没发现,在st测试的时候报了这个错误。“Comparison method violates its general contract!”。

具体堆栈信息:

看起来没什么问题,但是却报了一个错,“比较方法违反其一般合同”。

在 JDK7 版本以上,Comparator 要满足自反性,传递性,对称性,不然 Arrays.sort,Collections.sort会报 IllegalArgumentException 异常。

自反性:当 两个相同的元素相比时,compare必须返回0,也就是compare(o1, o1) = 0;

反对称性:如果compare(o1,o2) = 1,则compare(o2, o1)必须返回符号相反的值也就是 -1;

传递性:如果 a>b, b>c, 则 a必然大于c。也就是compare(a,b)>0, compare(b,c)>0, 则compare(a,c)>0

报错代码:

public static Integer getOrderByCode(Integer clueDataChannel){
        if (clueDataChannel == null || lookup.get(clueDataChannel) == null){
            return MAX_ORDER;
        }
        return lookup.get(clueDataChannel).getOrder();
    }

问题原因:

解决办法:不要出现模棱两可的order!!!

public static Integer getOrderByCode(Integer clueDataChannel){
        if (clueDataChannel == null || lookup.get(clueDataChannel) == null){
            return Optional.ofNullable(clueDataChannel).orElse(0) + MAX_ORDER;
        }
        return lookup.get(clueDataChannel).getOrder();
    }
经验分享 程序员 微信小程序 职场和发展