Question

Collections.sort(cells, new Comparator<MyCell>() {

        @Override
        public int compare(MyCell o1, MyCell o2) {
            if (o1.getX() <= o2.getX() && o1.getY() <= o2.getY()) {
                return -1;
            } else {
                return 1;
            }
        }

    });

Here the full stack trace:

Exception in thread "main" java.lang.IllegalArgumentException: Comparison method violates its general contract!
at java.util.TimSort.mergeHi(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.TimSort.sort(Unknown Source)
at java.util.Arrays.sort(Unknown Source)
at java.util.Collections.sort(Unknown Source)

I know there are many questions like this one but I don't get it why my comparision is wrong. getX() and getY() returns a long. So how can I fix this?

I already search for it, but didn't get an answer.

Thanks in advance.

Was it helpful?

Solution

Here is a good answer on the topic. A comparator must be transitive to work. Otherwise, you would not get the same results from different orderings of the initial items.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top