"java.lang.IllegalArgumentException: Comparison method violates its general contract!" Collections.sort() 错误

"java.lang.IllegalArgumentException: Comparison method violates its general contract!" error for a Collections.sort()

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

//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;
                    }
                });

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

如果两个对象相等,你的比较器不会return0。

看到这个post:Comparison Method violates its general contract in Java 7