我正在尝试对x和y点的集合进行排序,其中x的偏移使得px-qx应该被视为等于IF px == qx OR ABS(px-qx)<offset.请注意,我在这里取绝对值,所以我不应该得到任何负值.我的比较器如下:
private static class XYOrder implements Comparator<ExtractPojo> {
public int compare(ExtractPojo p, ExtractPojo q) {
Integer a=p.x.intValue();
Integer b=q.x.intValue();
Integer c=p.y.intValue();
Integer d=q.y.intValue();
int offset=Math.abs(a-b); //calculate offset from x
if(offset < 15 || a == b) //if x is the same, sort by y coordinate
return c-d;
else return a-b; //if x is not same sort by x coordinate
}
}
Run Code Online (Sandbox Code Playgroud)
此代码适用于某些情况,但我在其他情况下收到以下错误消息:
Exception in thread "main" java.lang.IllegalArgumentException: Comparison method violates its general contract!
at java.util.TimSort.mergeHi(TimSort.java:868) …Run Code Online (Sandbox Code Playgroud)