-4 java sorting comparator java-8
虽然我使用下面的比较器来对我正在获得的对象进行排序比较方法违反了比较器中的一般合同问题.
final Set<Span> set = new TreeSet<Span>(new Comparator<Span>() {
public int compare(final Span firstSpan, final Span secSpan) {
BigInteger s1X0 = firstSpan.getCoordinates().getX0();
BigInteger s1X1 = firstSpan.getCoordinates().getX1();
BigInteger s2X0 = secSpan.getCoordinates().getX0();
BigInteger s2X1 = secSpan.getCoordinates().getX1();
BigInteger s1Y0 = firstSpan.getCoordinates().getY0();
final BigInteger s2Y0 = secSpan.getCoordinates().getY0();
if(s1X0.intValue() == s2X0.intValue() && s1X1.intValue() == s2X1.intValue() && s1Y0.intValue() == s2Y0.intValue()){
return 0;
}
if ((s1Y0.intValue() - s2Y0.intValue() <= 5) && (s1Y0.intValue() - s2Y0.intValue() >= -5)) {
return (s1X0.intValue()>s2X0.intValue()) ? 1 : -1;
} else {
if ((s1X0.intValue() >= s2X0.intValue() && s1X0.intValue() <= s2X1.intValue())
|| (s2X0.intValue() >= s1X0.intValue() && s2X0.intValue() <= s1X1.intValue())) {
return (s1Y0.intValue() > s2Y0.intValue()) ? 1 : -1;
} else {
return s1X0.intValue() > s2X0.intValue() ? 1 : -1;
}
}
}
});
Run Code Online (Sandbox Code Playgroud)
一个Comparator必须征收总排序就可以比较的对象.特别地,这意味着它必须是可传递的,即,如果a小于b,并且b小于c,则a必须小于c.你Comparator没有那个属性.
请考虑以下示例:
a.getX0() == 1 b.getX0() == 2 c.getX0() == 3
a.getX1() == 4 b.getX1() == 5 c.getX1() == 6
a.getY0() == 4 b.getY0() == 0 c.getY0() == -4
Run Code Online (Sandbox Code Playgroud)
然后它保持a小于b(y0的差小于5),b小于c(差值是y0小于5),但a不小于c(y0的差大于5,所以y0取值).
这三个对象应按什么顺序排序?
此外,您的代码还有其他问题.如果将所有内容转换为a int,可能会发生溢出(这也可能导致您提到的异常).当数据存储为时BigInteger,您还应该使用BigIntegers 进行比较,例如使用方法BigInteger.subtract和BigInteger.compare.