Java自定义排序异常:Comparison method violates its general contract


java.lang.IllegalArgumentException: Comparison method violates its general contract!
  at line 781, java.base/java.util.TimSort.mergeLo
  at line 518, java.base/java.util.TimSort.mergeAt
  at line 448, java.base/java.util.TimSort.mergeCollapse
  at line 245, java.base/java.util.TimSort.sort
  at line 1442, java.base/java.util.Arrays.sort
  at line 3, Solution.merge
  at line 54, __DriverSolution__.__helper__
  at line 84, __Driver__.main

示例:对 int[][] intervals 二维数组进行排序

错误的写法:

 Arrays.sort(intervals, (first, end) -> {
     if(first[0] < end[0]){
         return -1;
     }
     return 1;
});

正确的写法

 Arrays.sort(intervals, (first, end) -> {
      if(first[0] < end[0]){
          return -1;
      }
      if(first[0] == end[0]){
          return first[1] - end[1];
      }
      return 1;
});

备注:first和end比较时,first.compareTo(end) > 0 时,必须满足:end.compareTo(first) < 0 否则会抛出异常。

你可能感兴趣的:(java,java,开发语言,后端)