gpt4 book ai didi

java - 比较方法违反了它的一般契约(数组列表比较)

转载 作者:行者123 更新时间:2023-12-01 14:36:43 26 4
gpt4 key购买 nike

我之前问过compare arraylists of chars alphabetically如何按字母顺序比较字符的数组列表。现在我决定实现它。

这是我的比较方法

@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,如果不等于,我开始比较数组列表的每个元素。但如果不相等,我会比较 leftright

但我不明白为什么它会抛出这样的异常。问题出在哪里?

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 的地方`。

最佳答案

一些评论:

if (this.get(i).compareTo(o.get(i)) < 0)
return 1;

这应该返回-1

catch(IndexOutOfBoundsException e){
return -1;
}

这个1(因为这个尺寸更大)

catch(IndexOutOfBoundsException e){
return 1;
}

这个-1(因为这个尺寸较小)

尝试进行这些更改..

关于java - 比较方法违反了它的一般契约(数组列表比较),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16430272/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com