" java.lang.IllegalArgumentException:比较方法违反了其一般合同!" Collections.sort()的错误

时间:2015-03-31 21:24:39

标签: java collections

我正在尝试对一堆数字进行排序并使用以下代码:

//sort possible targets based on distance
                Collections.sort(allPossibleTargets, new Comparator<NPD2>() {
                    @Override
                    public int compare(NPD2 o1, NPD2 o2) {
                        if (o1 == null && o2 == null)
                            return 0;
                        if (o1 == null && o2 != null)
                            return 1;
                        if (o1 != null && o2 == null)
                            return -1;
                        return o1.getNpd().getDistance() < o2.getNpd().getDistance() ? -1 : 1;
                    }
                });

但是,我得到了上述异常。请帮忙。感谢。

1 个答案:

答案 0 :(得分:0)

如果两个对象相等,则比较器不返回0。

请参阅此帖子:Comparison Method violates its general contract in Java 7