java.lang.IllegalArgumentException: Comparison method violates its general contract! 报错
代码:
public static void wbsSort(List<SendMessageEntity> sendMessageEntityList){ Collections.sort(sendMessageEntityList, (o1, o2) -> { String wbsCode1Temp = o1.getWbsCode(); String wbsCode2Temp = o2.getWbsCode(); String wbsCode1 = wbsCode1Temp.replaceAll("\\.",""); String wbsCode2 = wbsCode2Temp.replaceAll("\\.",""); int pointNum1 = 9-wbsCode1Temp.split("\\.").length; int pointNum2 = 9-wbsCode2Temp.split("\\.").length; String zero1 = ""; String zero2 = ""; for(int index=0;index<pointNum1;index++){ zero1 += "0"; } for(int index=0;index<pointNum2;index++){ zero2 += "0"; } wbsCode1 = wbsCode1+ zero1; wbsCode2 = wbsCode2 +zero2; // 转换为long类型 long wbsCodeLong1 = Long.parseLong(wbsCode1); long wbsCodeLong2 = Long.parseLong(wbsCode2); if(wbsCodeLong1 > wbsCodeLong2){ return 1; }else{ return -1; } }); }
解决办法:
你的比较方法有可能违反了比较合同,因为当 wbsCodeLong1
和 wbsCodeLong2
相等时,方法没有处理平等的情况。你应该在 if
语句之后添加处理相等情况的逻辑,如下:
return Long.compare(wbsCodeLong1, wbsCodeLong2);
里使用 Long.compare
方法来简化比较逻辑,并处理相等情况。这应当符合比较方法的合同,避免异常。
public static void wbsSort(List<SendMessageEntity> sendMessageEntityList){ Collections.sort(sendMessageEntityList, (o1, o2) -> { String wbsCode1Temp = o1.getWbsCode(); String wbsCode2Temp = o2.getWbsCode(); String wbsCode1 = wbsCode1Temp.replaceAll("\\.",""); String wbsCode2 = wbsCode2Temp.replaceAll("\\.",""); int pointNum1 = 9 - wbsCode1Temp.split("\\.").length; int pointNum2 = 9 - wbsCode2Temp.split("\\.").length; String zero1 = String.format("%0" + pointNum1 + "d", 0); String zero2 = String.format("%0" + pointNum2 + "d", 0); wbsCode1 = wbsCode1 + zero1; wbsCode2 = wbsCode2 + zero2; long wbsCodeLong1 = Long.parseLong(wbsCode1); long wbsCodeLong2 = Long.parseLong(wbsCode2); return Long.compare(wbsCodeLong1, wbsCodeLong2); }); }