Collections.sort() 抛出比较方法违反了其总协定!例外
2022-09-01 23:38:47
我正在尝试对List<>对象进行排序,并引发此异常(仅适用于大型列表)
排序代码:
List<FinalSentence> sentenceList = finalRepresentation.getSentences();
Collections.sort(sentenceList); // <=== EXCEPTION THROWN HERE!!!
FinalSentence 类标头:
public class FinalSentence implements Comparable<FinalSentence>{...}
compareTo() 实现:
@Override
public int compareTo(FinalSentence o) {
if (this == o) {
return 0;
}
if (this.score > o.score) {
return 1;
}
if (this.score < o.score) {
return -1;
}
return 0;
}
这是例外:
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 feature.finalRepresentation.Summarizer.summarize(Summarizer.java:30)
at driver.Driver.main(Driver.java:114)
对于一个小列表(少于50个元素),它的工作原理。对于一个大列表(它也应该与那些一起工作),它会抛出这个异常。列表的实例类型是 ArrayList,这并不重要。
我不知道如何弄清楚这一点。列表是完整的,元素是相同的类型(那里没有多态性),但我得到了这个奇怪的例外,用于大型列表。
有什么想法吗?
提前致谢!!!