Java error: Comparison method violates its general contract

前端 未结 10 2322
别跟我提以往
别跟我提以往 2020-11-22 04:17

I saw many questions about this, and tried to solve the problem, but after one hour of googling and a lots of trial & error, I still can\'t fix it. I hope some of you ca

10条回答
  •  不要未来只要你来
    2020-11-22 05:12

    I ran into a similar problem where I was trying to sort a n x 2 2D array named contests which is a 2D array of simple integers. This was working for most of the times but threw a runtime error for one input:-

    Arrays.sort(contests, (row1, row2) -> {
                if (row1[0] < row2[0]) {
                    return 1;
                } else return -1;
            });
    

    Error:-

    Exception in thread "main" java.lang.IllegalArgumentException: Comparison method violates its general contract!
        at java.base/java.util.TimSort.mergeHi(TimSort.java:903)
        at java.base/java.util.TimSort.mergeAt(TimSort.java:520)
        at java.base/java.util.TimSort.mergeForceCollapse(TimSort.java:461)
        at java.base/java.util.TimSort.sort(TimSort.java:254)
        at java.base/java.util.Arrays.sort(Arrays.java:1441)
        at com.hackerrank.Solution.luckBalance(Solution.java:15)
        at com.hackerrank.Solution.main(Solution.java:49)
    

    Looking at the answers above I tried adding a condition for equals and I don't know why but it worked. Hopefully we must explicitly specify what should be returned for all cases (greater than, equals and less than):

            Arrays.sort(contests, (row1, row2) -> {
                if (row1[0] < row2[0]) {
                    return 1;
                }
                if(row1[0] == row2[0]) return 0;
                return -1;
            });
    

提交回复
热议问题