Java error: Comparison method violates its general contract

前端 未结 10 2141
别跟我提以往
别跟我提以往 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 05:07

    I got the same error with a class like the following StockPickBean. Called from this code:

    List beansListcatMap.getValue();
    beansList.sort(StockPickBean.Comparators.VALUE);
    
    public class StockPickBean implements Comparable {
        private double value;
        public double getValue() { return value; }
        public void setValue(double value) { this.value = value; }
    
        @Override
        public int compareTo(StockPickBean view) {
            return Comparators.VALUE.compare(this,view); //return 
            Comparators.SYMBOL.compare(this,view);
        }
    
        public static class Comparators {
            public static Comparator VALUE = (val1, val2) -> 
    (int) 
             (val1.value - val2.value);
        }
    }
    

    After getting the same error:

    java.lang.IllegalArgumentException: Comparison method violates its general contract!

    I changed this line:

    public static Comparator VALUE = (val1, val2) -> (int) 
             (val1.value - val2.value);
    

    to:

    public static Comparator VALUE = (StockPickBean spb1, 
    StockPickBean spb2) -> Double.compare(spb2.value,spb1.value);
    

    That fixes the error.

提交回复
热议问题