Comparison method violates its general contract!
程序员文章站
2024-02-23 08:01:40
...
今天在刷LeetCode题目的时候,问题使用HashMap按照value排序来解决,自定义比较器,但是报错:java.lang.IllegalArgumentException: Comparison method violates its general contract!
原比较器的写法:
Comparator<Map.Entry<Integer, Integer>> byMapValues = new Comparator<Map.Entry<Integer, Integer>>() {
@Override
public int compare(Map.Entry<Integer, Integer> left, Map.Entry<Integer, Integer> right) {
if (left.getValue()<right.getValue()) return 1;
else return -1;
}
};
之后正确的写法:
Comparator<Map.Entry<Integer, Integer>> byMapValues = new Comparator<Map.Entry<Integer, Integer>>() {
@Override
public int compare(Map.Entry<Integer, Integer> left, Map.Entry<Integer, Integer> right) {
return right.getValue().compareTo(left.getValue());
}
};
大概的原因是JDK1.7版本的问题,替换了java.util.Arrays.sort排序算法的实现。具体可以参考这里。
下一篇: Hadoop小试牛刀之dump数据
推荐阅读
-
Comparison method violates its general contract!
-
Comparison method violates its general contract
-
Comparison method violates its general contract!
-
Comparison method violates its general contract!
-
Comparison method violates its general contract!
-
Comparison method violates its general contract
-
java中排序报:Comparison method violates its general contract异常的解决
-
java中排序报:Comparison method violates its general contract异常的解决
-
java 排序报:Comparison method violates its general contract异常的解决方法
-
java 排序报:Comparison method violates its general contract异常的解决方法