0

I was sorting an 2D int array when doint a leetcode question https://leetcode.com/problems/merge-intervals/

First, I used custom comparator but one testcase gives me java.lang.IllegalArgumentException: Comparison method violates its general contract!

Arrays.sort(intervals,new Comparator<int[]>(){
    @Override
    public int compare(int[] a,int[] b){
        return a[0]>b[0]? 1:-1;
    }
});

However, lambda expression below does not show any Exception:

Arrays.sort(intervals, (a, b) -> a[0] - b[0]);

the failing testcase is something like this but array length is much much longer: [[3,4],[1,5],[64,66],[73,77],[90,94],[20,21],[84,87],[48,49],[80,80]]

I'm super confused and would appreciate if someone can show me the difference :)

Talenel
  • 422
  • 2
  • 6
  • 25
  • They're not the same formula. `a[0] - b[0]` doesn't ([usually](https://stackoverflow.com/a/2728810/1553851)) violate reflexivity. – shmosel Dec 15 '21 at 03:57
  • The difference has nothing to do with lambda syntax vs. anonymous class syntax. It's because they have different implementations. Hint: what value will each version return when `a[0]` and `b[0]` have the same value? – Tim Moore Dec 15 '21 at 03:58
  • If the values are equal, you don't return 0. So, if a=3 and b=3, then your function returns -1 in both (a,b) and (b,a), and that violates the contract. – Tim Roberts Dec 15 '21 at 03:59
  • Thanks @TimRoberts adding return 0 for equal conditions did fix the issue./ but with the format I post in question, even if I don't include the equal condition, most testcases will pass. why those testcases pass? – Fei Gao Dec 15 '21 at 04:27
  • @TimMoore Thanks, adding return 0 fix this issue. But do you know why most of the testcases still passed without returning 0? – Fei Gao Dec 15 '21 at 04:29
  • @FeiGao for the purposes of sorting, it doesn't always matter whether two elements are equal, because you have to choose some order to put them in. – Tim Moore Dec 15 '21 at 04:32

0 Answers0