栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

排序问题排查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();
    }

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/345950.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号