JAVA 排序方法异常:比较方法违反了它的一般契约
JAVA sort method exception : Comparison method violates its general contract
很抱歉这个重复的问题已经在其他帖子上得到了回答。不幸的是,我不知道如何在我的代码中实现它:
public int compare(Group gp1, Group gp2){
if (gp1.isPredOf(gp2))
return 1;
if (gp2.isPredOf(gp1))
return -1;
return 0;
}
请注意,如果 gp1
是 gp2
的前身,则 gp2.isPredOf(gp1)
将 return false
反之亦然。
你能告诉我避免这个异常的适当代码吗?
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: Comparison method violates its general contract!
感谢您的帮助。
PS : 函数代码 "isPredOf" :
public boolean isPredOf(Group gp2){
for (Operation op1 : this.operations){
for (int i=0;i<=op1.job.operations.indexOf(op1);i++){
if (gp2.operations.contains(op1.job.operations.get(i)))
return true;
}
}
return false;
}
您的 isPredOf
可能不尊重传递性。检查空参数,它们可能会产生此类问题。
官方文档(http://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html)说:
The implementor must ensure that sgn(compare(x, y)) == -sgn(compare(y, x)) for all x and y. (This implies that compare(x, y) must throw an exception if and only if compare(y, x) throws an exception.)
The implementor must also ensure that the relation is transitive: ((compare(x, y)>0) && (compare(y, z)>0)) implies compare(x, z)>0.
Finally, the implementor must ensure that compare(x, y)==0 implies that sgn(compare(x, z))==sgn(compare(y, z)) for all z.
很抱歉这个重复的问题已经在其他帖子上得到了回答。不幸的是,我不知道如何在我的代码中实现它:
public int compare(Group gp1, Group gp2){
if (gp1.isPredOf(gp2))
return 1;
if (gp2.isPredOf(gp1))
return -1;
return 0;
}
请注意,如果 gp1
是 gp2
的前身,则 gp2.isPredOf(gp1)
将 return false
反之亦然。
你能告诉我避免这个异常的适当代码吗?
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: Comparison method violates its general contract!
感谢您的帮助。
PS : 函数代码 "isPredOf" :
public boolean isPredOf(Group gp2){
for (Operation op1 : this.operations){
for (int i=0;i<=op1.job.operations.indexOf(op1);i++){
if (gp2.operations.contains(op1.job.operations.get(i)))
return true;
}
}
return false;
}
您的 isPredOf
可能不尊重传递性。检查空参数,它们可能会产生此类问题。
官方文档(http://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html)说:
The implementor must ensure that sgn(compare(x, y)) == -sgn(compare(y, x)) for all x and y. (This implies that compare(x, y) must throw an exception if and only if compare(y, x) throws an exception.)
The implementor must also ensure that the relation is transitive: ((compare(x, y)>0) && (compare(y, z)>0)) implies compare(x, z)>0.
Finally, the implementor must ensure that compare(x, y)==0 implies that sgn(compare(x, z))==sgn(compare(y, z)) for all z.