谁能简单地解释一下,为什么这段代码抛出一个异常,“比较方法违反了它的一般契约!”,以及我该如何修复它?

private int compareParents(Foo s1, Foo s2) {
    if (s1.getParent() == s2) return -1;
    if (s2.getParent() == s1) return 1;
    return 0;
}

当前回答

在我的例子中,它是无限排序。 也就是说,首先这条线根据条件向上移动,然后这条线向下移动到相同的位置。 我在最后添加了一个条件,明确地建立了行序。

其他回答

只是因为这是我得到的当我谷歌这个错误,我的问题是我有

if (value < other.value)
  return -1;
else if (value >= other.value)
  return 1;
else
  return 0;

>= other。Value(显然)实际上应该是Value > other。值,这样你就可以用相等的对象返回0。

在我们的例子中,我们得到这个错误是因为我们不小心颠倒了s1和s2比较的顺序。所以要小心。它显然比下面的要复杂得多,但这是一个例子:

s1 == s2   
    return 0;
s2 > s1 
    return 1;
s1 < s2 
    return -1;

你不能像这样比较对象数据:s1.getParent() == s2 -这将比较对象引用。你应该重写Foo类的equals函数然后像这样比较它们s1.getParent()。equals(s2)

以我为例,我做了如下事情:

if (a.someField == null) {
    return 1;
}

if (b.someField == null) {
    return -1;
}

if (a.someField.equals(b.someField)) {
    return a.someOtherField.compareTo(b.someOtherField);
}

return a.someField.compareTo(b.someField);

我忘记检查的是当a.someField和b.someField都为空时。

在我的例子中,它是无限排序。 也就是说,首先这条线根据条件向上移动,然后这条线向下移动到相同的位置。 我在最后添加了一个条件,明确地建立了行序。