在按字母顺序比较字符数组列表之前,我问过如何按字母顺序比较字符数组列表。现在我决定实施它。
这是我的比较方法
@Override
public int compareTo(Word o) {
int left = this.count();
int right = o.count();
if (left == right){
if (this.length() > o.length()){
try{
for(int i = 0; i < this.length(); i++){
if (this.get(i).compareTo(o.get(i)) < 0)
return 1;
}
}catch(IndexOutOfBoundsException e){
return -1;
}
}
else {
try{
for(int i = 0; i < o.length(); i++){
if (this.get(i).compareTo(o.get(i)) < 0)
return -1;
}
}catch(IndexOutOfBoundsException e){
return 1;
}
}
}
else return (left > right)?1:-1;
return 0;
}
我检查是否this.count
等于o.count
,如果不等于,我开始比较数组列表的每个元素。但如果它不相等,那么我比较left
and right
。
但我不明白为什么它会抛出这样的异常。问题出在哪里?
Exception in thread "main" java.lang.IllegalArgumentException: Comparison method violates its general contract!
at java.util.ComparableTimSort.mergeHi(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.ComparableTimSort.sort(Unknown Source)
at java.util.Arrays.sort(Unknown Source)
at java.util.Collections.sort(Unknown Source)
at task.Main.main(Main.java:69)
Main.java: 69
是调用的地方Collections.sort
`。