简体   繁体   中英

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. 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. Try and add a case for yIndex_0 == yIndex_1 that returns 0 .

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;

    }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM