[英]Error when sorting array list using a comparator in Java
親愛的程序員,我一直在嘗試實現一個排序系統,通過圖像的高度和 y 坐標對圖像進行排序。 但是,每次我嘗試運行它時,幾秒鍾后都會出現錯誤。
錯誤
Exception in thread "Thread-2" java.lang.IllegalArgumentException: Comparison method violates its general contract!
at java.util.TimSort.mergeLo(Unknown Source)
at java.util.TimSort.mergeAt(Unknown Source)
at java.util.TimSort.mergeCollapse(Unknown Source)
at java.util.TimSort.sort(Unknown Source)
at java.util.Arrays.sort(Unknown Source)
at java.util.ArrayList.sort(Unknown Source)
排序的列表:
ArrayList<Image> list = new ArrayList<Image>();
list.sort(imageSorter);
分揀機:
public static final Comparator<Image> imageSorter = new Comparator<Image>() {
// indexes used to calculate the sorting \\
float yIndex_0, yIndex_1;
public int compare(Imageimage_0, Imageimage_1) {
yIndex_0 = image_0.y + image_0.height;
yIndex_1 = image_1.y + image_1.height;
if(yIndex_0 < yIndex_1) {
return -1;
}
return 1;
}
};
我已經嘗試了很多方法來解決這個問題,包括下面的部分,但沒有成功。
我試圖添加部分來解決這個問題。
if(image_0 == null || image_1 == null) {
if(image_0 == image_1) {
return 0;
}else if (image_0 == null) {
return -1;
}
return 1;
}
如果您知道任何嘗試解決此問題的方法,請告訴我。
提前致謝。
這可能是因為您的比較不具有傳遞性。 例如,如果A
和B
相等,比較(A,B)
會告訴您A
更大,而比較(B,A)
會告訴您B
更大。 嘗試為yIndex_0 == yIndex_1
添加一個返回0
的案例。
您需要在 Comparator yIndex_0 == yIndex_1 return 0 中再添加一個條件。
public static final Comparator<Image> imageSorter = new Comparator<Image>() {
// indexes used to calculate the sorting \\
float yIndex_0, yIndex_1;
public int compare(Imageimage_0, Imageimage_1) {
yIndex_0 = image_0.y + image_0.height;
yIndex_1 = image_1.y + image_1.height;
if(yIndex_0 == yIndex_1) {
return 0;
} elseif(yIndex_0 < yIndex_1) {
return -1;
}
return 1;
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.