我刚刚编写了一个测试程序来违反使用Tim Sort的Java 7的compareTo方法中的传递性。以下是我比较的实现。
@Override
public int compareTo(ComparableObject o) {
if (o.getId() != 0 && this.getId() != 0) {
if (o.getId() < this.getId()) {
return 1;
} else if (o.getId() > this.getId()) {
return -1;
} else {
return 0;
}
}
return 0;
}
正如预期的那样,当我尝试运行程序时会抛出以下异常,因为它违反了传递性 -
Exception in thread "main" java.lang.IllegalArgumentException: Comparison method violates its general contract!
at java.util.ComparableTimSort.mergeLo(Unknown Source)
at java.util.ComparableTimSort.mergeAt(Unknown Source)
at java.util.ComparableTimSort.mergeCollapse(Unknown Source)
at java.util.ComparableTimSort.sort(Unknown Source)
at java.util.Arrays.sort(Unknown Source)
at java.util.Arrays.sort(Unknown Source)
at java.util.ArrayList.sort(Unknown Source)
at java.util.Collections.sort(Unknown Source)
at MainClass.main(MainClass.java:24)
检查零(对于整数)或null(对于String或任何其他对象)值的最佳方法是什么,只有在它们不为零或为零且没有得到Tim Sort异常时才比较2个元素?如何编写上面的代码,以便我不会得到错误但只比较非零整数?