When does TimSort complain about broken comparator?

后端 未结 2 2097
小蘑菇
小蘑菇 2021-01-03 02:35

Java 7 changed the sorting algorithm such that it throws an

java.lang.IllegalArgumentException: \"Comparison method violates its general contract!\"<

2条回答
  •  萌比男神i
    2021-01-03 02:42

    From the documentation:

    IllegalArgumentException - (optional) if the natural ordering of the array elements is found to violate the Comparable contract

    I didn't find much on the mentioned contract, but IMHO it should represent a total order (ie the relation defined by the compareTo method has to be transitive, antisymmetric, and total). If that requirement isn't met, sort might throw an IllegalArgumentException. (I say might because failure to meet this requirement could go unnoticed.)

    EDIT: added links to the properties that make a relation a total order.

提交回复
热议问题