zhli219 2018-01-23 09:26 采纳率: 40%
浏览 3331
已采纳

Collections.sort报错,大神求分析、求答案

 Collections.sort(lcd1, new Comparator<CouponDto>(){
                    @Override
                    public int compare(CouponDto o1, CouponDto o2) {
                            if(o1.getCoupon().getListOrder2() > o2.getCoupon().getListOrder2()){
                                return -1;
                            }
                            if(o1.getCoupon().getListOrder2() == o2.getCoupon().getListOrder2()){
                                return 0;
                            }
                            return  1;
                    };

                });
    报Comparison method violates its general contract异常
            改成
    Collections.sort(lcd1, new Comparator<CouponDto>(){
                    @Override
                    public int compare(CouponDto o1, CouponDto o2) {
                            return -(o1.getCoupon().getListOrder2() - o2.getCoupon().getListOrder2());
                    };

                });
            就不再报错;
            各位大神,这个是怎么回事
  • 写回答

5条回答 默认 最新

  • threenewbee 2018-01-23 15:44
    关注
     鄙视胡乱在网上抄一个答案的。
    
    你的代码虽然满足了自反性,但是不满足偏序。jdk 1.7还要求偏序性。
    比如a = 10 b = 8 c = 4,那么你的代码出现 comp(a,b) == comp(a, c),sort会假设b=c但是实际上是b>c
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?