很抱歉这个重复的问题已在其他帖子中得到解答。不幸的是我不知道如何在我的代码上实现它:
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)
将返回false
,反之亦然。
您能否告诉我适当的代码以避免此异常?
线程中的异常“AWT-EventQueue-0”java.lang.IllegalArgumentException:比较方法违反了其一般合同!
感谢您的帮助。
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;
}
答案 0 :(得分:0)
你的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.