Comparable interface depends on the size?

I worked on the interface Comparableand found that it throws IllegalArgumentExceptionwhen I put size=50in the program below and works fine when I put size =5.

    public class Test {
    public static void main(String[] args) {
        int size = 50;
        Test compareTest = new Test();
        compareTest.test(size);
    }

    public void test(int size) {
        List<TestObject> requests = new ArrayList<TestObject>();
        for (int index = 0; index < size; index++) {
            TestObject request = new TestObject();
            request.value = index;
            requests.add(request);
        }
        Collections.sort(requests);
    }

}

class TestObject implements Comparable<TestObject> {
    public int value;

    public int compareTo(TestObject req) {
        if (value % 3 == 0) {
            return -1;
        } else if (value % 3 == 1) {
            return 0;
        }

        return 1;
    }
}

I am not sure about the root cause of this problem, can anyone help me with this.

The exception stack trace is shown below.

Exception in thread "main" java.lang.IllegalArgumentException: Comparison method violates its general contract!
    at java.util.ComparableTimSort.mergeLo(ComparableTimSort.java:744)
    at java.util.ComparableTimSort.mergeAt(ComparableTimSort.java:481)
    at java.util.ComparableTimSort.mergeCollapse(ComparableTimSort.java:406)
    at java.util.ComparableTimSort.sort(ComparableTimSort.java:213)
+4
source share
3 answers

You are breaking a contract with comparable ones.

Actually, you do not compare two objects between them, but you only compare the field of the valuecurrent object TestObjectin accordance with the result modulo 3. You do not use the object TestObjectpassed as a parameter in the method compareTo().

, List TestObject 3 value

-1:

    if (value % 3 == 0) {
        return -1;
    } 

:

sgn (x.compareTo(y)) == -sgn (y.compareTo(x)) x y. ( , x.compareTo(y) iff y.compareTo(x) .)

, x, y.
y.compareTo(x) (, -1), x.compareTo(y) (, 1).

Comparable , IllegalArgumentException, = 50 , size = 5

, Comparable, . , .
JVM .
, , , .
, , . , . API.

+6

, Collections.sort Arrays.sort TimSort, in 32, binary insertion sort, .

size >32 java.lang.IllegalArgumentException: ! " , compareTo .

+3

, compareTo .

compareTo () :

(1) x.compareTo(x) 0.

(2) x.compareTo(y) 0, y.compareTo(x) 0; x.compareTo(y) > 0, y.compareTo(x) < 0 .

(3) x.compareTo(y) y.compareTo(z) > 0, x.compareTo(z) > 0; , 0, < 0 (). .

; compareTo , . , .

Timsort , ; , compareTo , , , . compareTo , , . . , , , .

+2

Source: https://habr.com/ru/post/1678385/


All Articles