[英]Error when sorting array list using a comparator in Java
Dear fellow programmers, I have been trying to implement a sorting system to sort images by its height plus the y coordinate.亲爱的程序员,我一直在尝试实现一个排序系统,通过图像的高度和 y 坐标对图像进行排序。 However every time I try to run it I get an error after a few seconds.但是,每次我尝试运行它时,几秒钟后都会出现错误。
Error错误
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)
List which gets sorted:排序的列表:
ArrayList<Image> list = new ArrayList<Image>();
list.sort(imageSorter);
Sorter:分拣机:
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;
}
};
I have tried many things for trying to fix this including the part below but with no success.我已经尝试了很多方法来解决这个问题,包括下面的部分,但没有成功。
Part i tried to add to fix this problem.我试图添加部分来解决这个问题。
if(image_0 == null || image_1 == null) {
if(image_0 == image_1) {
return 0;
}else if (image_0 == null) {
return -1;
}
return 1;
}
If you know any methods to try to fix this problem, please let me know.如果您知道任何尝试解决此问题的方法,请告诉我。
Thanks in advance.提前致谢。
It might be because your comparison is not transitive.这可能是因为您的比较不具有传递性。 Eg, if A
and B
is equal, comparing (A,B)
will tell you that A
is greater while comparing (B,A)
will tell you that B
is greater.例如,如果A
和B
相等,比较(A,B)
会告诉您A
更大,而比较(B,A)
会告诉您B
更大。 Try and add a case for yIndex_0 == yIndex_1
that returns 0
.尝试为yIndex_0 == yIndex_1
添加一个返回0
的案例。
You need to add one more condition in Comparator yIndex_0 == yIndex_1 return 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.