谁能简单地解释一下,为什么这段代码抛出一个异常,“比较方法违反了它的一般契约!”,以及我该如何修复它?
private int compareParents(Foo s1, Foo s2) {
if (s1.getParent() == s2) return -1;
if (s2.getParent() == s1) return 1;
return 0;
}
谁能简单地解释一下,为什么这段代码抛出一个异常,“比较方法违反了它的一般契约!”,以及我该如何修复它?
private int compareParents(Foo s1, Foo s2) {
if (s1.getParent() == s2) return -1;
if (s2.getParent() == s1) return 1;
return 0;
}
当前回答
在我们的例子中,我们得到这个错误是因为我们不小心颠倒了s1和s2比较的顺序。所以要小心。它显然比下面的要复杂得多,但这是一个例子:
s1 == s2
return 0;
s2 > s1
return 1;
s1 < s2
return -1;
其他回答
以我为例,我做了如下事情:
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都为空时。
违反合同通常是指比较者在比较对象时没有提供正确或一致的值。例如,你可能想要执行一个字符串比较,并强制空字符串排序到最后:
if ( one.length() == 0 ) {
return 1; // empty string sorts last
}
if ( two.length() == 0 ) {
return -1; // empty string sorts last
}
return one.compareToIgnoreCase( two );
但是这忽略了1和2都为空的情况——在这种情况下,返回了错误的值(1而不是0以显示匹配),比较器将其报告为违规。它应该写成:
if ( one.length() == 0 ) {
if ( two.length() == 0 ) {
return 0; // BOth empty - so indicate
}
return 1; // empty string sorts last
}
if ( two.length() == 0 ) {
return -1; // empty string sorts last
}
return one.compareToIgnoreCase( two );
如果compareParents(s1, s2) == -1,则期望compareParents(s2, s1) == 1。对于你的代码,这并不总是正确的。
具体来说,如果s1. getparent () == s2 && s2. getparent () == s1。 这只是可能出现的问题之一。
只是因为这是我得到的当我谷歌这个错误,我的问题是我有
if (value < other.value)
return -1;
else if (value >= other.value)
return 1;
else
return 0;
>= other。Value(显然)实际上应该是Value > other。值,这样你就可以用相等的对象返回0。
我也遇到过同样的问题,但我解决了。
//This this your code
private int compareParents(Foo s1, Foo s2) {
if (s1.getParent() == s2) return -1;
if (s2.getParent() == s1) return 1;
return 0;
}
违例是将不同的事物相互比较。
//acceptable
compare between s1.getParent() and s2.getParent()
//acceptable
compare between s1 and s2
//NOT acceptable
compare between s1 and s2.getParent()
//NOT acceptable
compare between s1.getParent() and s2
在我的代码中,我想通过地址的协调来排序。在比较器中,我错误地比较了X和Y,而不是X和X。
//My code:
private void sortBasedOnX(){
//addresses is a list of addresses where each address has X and Y
addresses.sort((o1, o2) -> {
String a = o1.getAddress().getX();
String b = o2.getAddress().getY(); //<-- this is supposed to be getX
return Integer.parseInt(a)-Integer.parseInt(b);
});
}
//acceptable
compare between o1.getAddress().getX() and o1.getAddress().getX()
//acceptable
compare between o1.getAddress().getY() and o1.getAddress().getY()
//NOT acceptable
compare between o1.getAddress().getX() and o1.getAddress().getY()
//NOT acceptable
compare between o1.getAddress().getX() and o1.getAddress()
//NOT acceptable
compare between o1.getAddress().getX() and o1