当前位置: 代码迷 >> 综合 >> 排序问题排查Comparison method violates its general contract!
  详细解决方案

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

热度:69   发布时间:2023-11-29 20:22:46.0

通过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();}

 

  相关解决方案