虽然我使用下面的比较器对一个对象进行排序,但我得到的比较方法违反了它在比较器中的一般合同问题。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;
}
}
}
});
鉴于您调用了'intValue()'24次,为什么不只是制作's1X0'等'int'变量?这会让你更容易帮助你,而且你的代码更易于阅读。 –
如果你告诉我们你想要达到的目标,并且理想地提供一个展示问题的[mcve],那么这也会有所帮助 - 举个具体的例子,我们应该很容易向你展示你的比较不一致的地方。 –
你明白那个错误信息的含义吗?仔细阅读['java.util.Comparator']的API文档(http://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html),它解释了实现的要求'比较'方法。您的实施违反了这些要求,因此您必须检查您的代码并进行调整以确保其符合要求。 – Jesper