排序问题排查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

报错代码:

        // 线索优先级排序
        // 1.根据来源渠道排序
        // 2.根据线索状态排序
        // 3.时间排序
        clueHostList.sort((first, second) -> {
            if (first.getDataChannel().equals(second.getDataChannel())){
                if (first.getFollowUpStatus().equals(first.getFollowUpStatus())){
                    return (int)(first.getGmtCreate().getTime() - second.getGmtCreate().getTime());
                }
                return ClueFollowUpStatusOrder.getOrderByCode(first.getFollowUpStatus()) - ClueFollowUpStatusOrder.getOrderByCode(second.getFollowUpStatus());
            }
            return ClueDataChanelOrder.getOrderByCode(first.getDataChannel()) - ClueDataChanelOrder.getOrderByCode(second.getDataChannel());
        });
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();
    }

 

  • 5
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值