实现compare方法的时候报错Comparison method violates its general contract!
报错原因:在sort排序中重写的方法一定要满足:可逆比较
那什么是可逆比较呢?
当 A,B运算结果相等时,需要返回0。如果不返回0 ,则 compare(A,B) , compare(B,A) 同时大于0,或者同时小于0,造成A,B排序混乱,进而会报如题的错误。
意思就是compare(A,B) , compare(B,A) 的结果应该是一样的才可以。
具体解决方法:
加一个A == B 返回0的判断
public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) {
if (o1.getValue() > o2.getValue()) {
return -1;
} else if (o1.getValue() == o2.getValue()) {
return 0;
}
return 1;
}