关于jdk7中 使用Collections的排序方法时报Comparison method violates its general contract!异常

参考:

  Comparison method violates its general contract

  Comparison method violates its general contract!

  比较器报错:Comparison method violates its general contract

  图解JDK7的Comparison method violates its general contract异常

主要是因为在compare的实现方法中,没有处理好两个比较对象相等的情况.

错误比较代码:

Collections.sort(entryList, new Comparator>()
{
@Override
public int compare(Map.Entry o1, Map.Entry o2)
{
return (o1.getValue() - o2.getValue() > 0 ? -1 : 1);
}
});

参考Float的compare方法(因为Float实现了Comparable<Float>接口):

    public static int compare(float f1, float f2) {
if (f1 < f2)
return -1; // Neither val is NaN, thisVal is smaller
if (f1 > f2)
return 1; // Neither val is NaN, thisVal is larger // Cannot use floatToRawIntBits because of possibility of NaNs.
int thisBits = Float.floatToIntBits(f1);
int anotherBits = Float.floatToIntBits(f2); return (thisBits == anotherBits ? 0 : // Values are equal
(thisBits < anotherBits ? -1 : // (-0.0, 0.0) or (!NaN, NaN)
1)); // (0.0, -0.0) or (NaN, !NaN)
}

所以错误代码应该改为: 

        Collections.sort(entryList, new Comparator<Map.Entry<String, Float>>()
{
@Override
public int compare(Map.Entry<String, Float> o1, Map.Entry<String, Float> o2)
{
return Float.compare(o1.getValue(),o1.getValue());
}
});

很多封装的数字对象都是有compare实现的.

上一篇:史上最简单的SpringCloud教程 | 第二篇: 服务消费者(rest+ribbon)


下一篇:[Android Pro] android root权限破解分析