gpt4 book ai didi

java - Kotlin 对象表达式 : Comparator example

转载 作者:IT老高 更新时间:2023-10-28 13:32:08 25 4
gpt4 key购买 nike

这段代码基本上是按降序对数组进行排序:

val arrayList = arrayListOf(1, 5, 2)

Collections.sort(arrayList, object : Comparator<Int> {
override fun compare(x : Int, y: Int) = y - x
})

究竟如何用 y - x 覆盖比较方法作品? Kotlin 如何知道 y - x表示放y之前 x如果 y < x ?

最佳答案

这实际上与 Kotlin 无关。它与 Java API 的 Comparator 接口(interface)以及 Collections.sort 如何使用它有关。

来自 the documentation:

Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.

现在让我们试试你给出的论点:

  • 1 - 5 = -4(负整数),因此 1 小于 5。
  • 5 - 2 = 3(一个正整数),所以 5 大于 2。
  • 等等……

Collections.sorty - x 的含义一无所知。它只是尊重任何实现者也需要尊重的 Comparator 接口(interface)的定义契约(Contract)(如果它想要工作)。

恰好 y - x 是一个尊重该契约的实现,因为 Math.

关于java - Kotlin 对象表达式 : Comparator example,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33441015/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com