[英]Sorting throws java.lang.IllegalArgumentException: Comparison method violates its general contract
I have this method that contains two comparators for sorting items by price. 我有这种方法,其中包含两个比较器,用于按价格对项目进行排序。
This works fine 90% of the time but sometimes it throws the exception in the title. 这在90%的时间内效果很好,但有时会在标题中引发异常。 Anyone know why
谁知道为什么
void sort(
Collections.sort(masterList, new Comparator<Item>() {
@Override
public int compare(Item o1, Item o2) {
try {
if (o1.getPriceLevel() == 999 && o1.getPriceLevel() < o2.getPriceLevel()) {
return 1;
}
if (o2.getPriceLevel() == 999) {
return -1;
}
return Double.compare(o1.getPriceLevel(), o2.getPriceLevel());
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
});
//Null pointer happens on the line below
Collections.sort(masterList, Collections.reverseOrder(new Comparator<Item>() {
@Override
public int compare(Item o1, Item o2) {
try {
if (o1.getPriceLevel() == 999 || o2.getPriceLevel() == 999) {
return 1;
}
return Double.compare(o1.getPriceLevel(), o2.getPriceLevel());
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
}));
}
edit: stacktrace 编辑:stacktrace
java.lang.IllegalArgumentException: Comparison method violates its general contract!
at java.util.TimSort.mergeLo(TimSort.java:743)
at java.util.TimSort.mergeAt(TimSort.java:479)
at java.util.TimSort.mergeCollapse(TimSort.java:406)
at java.util.TimSort.sort(TimSort.java:210)
at java.util.TimSort.sort(TimSort.java:169)
at java.util.Arrays.sort(Arrays.java:2038)
at java.util.Collections.sort(Collections.java:1891)
This is a check in the TimSort algorithm used by Java7 - which validates that your comparator method is valid ( eg symetric- a == b && b == a ) 这是对Java7使用的TimSort算法的检查-验证您的比较器方法是否有效(例如symetric- a == b && b == a)
your equals case is invalid (returning 0) - it depends on the order the arguments are given if one element is null. 您的equals大小写无效(返回0)-它取决于一个元素为null时给定参数的顺序。 Try to handle null values explicitly before doing anything else eg:
在执行其他任何操作之前,尝试显式处理null值,例如:
if(o1 == null || o2 == null)
{
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.