寫比較器出現ava.lang.IllegalArgumentException: Comparison method violates its general contract!異常

Arrays.sort(intervals, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                if(o1[0]> o2[0]) return 1;
                else if(o1[0] < o2[0]) return -1;
                else{
                    if(o1[1]>=o2[1])return 1;
                    else return -1;
                }
            }
        });

這個異常是說比較器不嚴謹,我認爲是缺少了return 0 的返回值,修改成下列程序就可以解決不bug

Arrays.sort(intervals, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                if(o1[0]> o2[0]) return 1;
                else if(o1[0] < o2[0]) return -1;
                else{
                    if(o1[1]>o2[1])return 1;
                    else if(o1[1]<o2[1]) return -1;
                }
                return 0;
            }
        });

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章