[英]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.