Reputation: 168
Dear fellow programmers, I have been trying to implement a sorting system to sort images by its height plus the y coordinate. 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.
Upvotes: 0
Views: 83
Reputation: 1344
You need to add one more condition in 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;
}
};
Upvotes: 1
Reputation: 569
It might be because your comparison is not transitive. E.g., 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. Try and add a case for yIndex_0 == yIndex_1
that returns 0
.
Upvotes: 1