反对称性, 即如果 a >= b 且 b >= a,则 a == b。 因此比较与相等性是有关系的,它们需要相互一致
传递性, 即如果 a >= b 且 b >= c,则 a >= c。 类似的,如果 a > b 且 b > c,则 a > c。这个特性很重要,因为如果没有了它,元素的排序可能会花费很长的时间
连通性,意味着任意两个元素间必定有一个关系。所以要么是 a >= b,要么是 b >= a 。在 Kotlin 中, compareTo 的类型系统保证了这一点,因为它返回 Int 值,每个 Int 要么是正的,要么是负的,要么是0。这很重要,因为如果两个元素之间没有联系,就不能使用快速排序或插入排序等经典算法。相反,我们需要使用一种特殊的算法来处理偏序,比如拓扑排序。
class User(val name: String, val surname: String) {
// ...
companion object {
val DISPLAY_ORDER =
compareBy(User::surname, User::name)
}
}
val sorted = names.sortedWith(User.DISPLAY_ORDER)
class User(
val name: String,
val surname: String
): Comparable<User> {
override fun compareTo(other: User): Int =
compareValues(surname, other.surname)
}
class User(
val name: String,
val surname: String
): Comparable<User> {
override fun compareTo(other: User): Int =
compareValuesBy(this, other, { it.surname }, { it.name })
}