这段代码基本上按降序排列数组:

val arrayList = arrayListOf(1, 5, 2)

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

How in the world does overriding the compare method with y - x works? How does Kotlin know what y - x means to put y before x if y < x?

推荐答案

This actually has nothing to do with Kotlin. It's related to the Java API's Comparator interface, and how Collections.sort uses it.

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.

Now let's try this out for the arguments you gave:

  • 1 - 5 = -4 (a negative integer), so 1 is less than 5.
  • 5-2=3(正整数),所以5大于2.
  • etc...

Collections.sort doesn't know anything about what y - x means. It simply respects the defined contract of the Comparator interface that any implementor also needs to respect (if it wants to work).

It just so happens that y - x is an implementation that does respect that contract, because Math.

Kotlin相关问答推荐

导入org.gradle.jvm.toolchain.internal.JavaToolchainFactory未解析引用:Java工具链工厂

禁用 Gradle执行消息

Kotlin - 如何避免在密封类的 when() 语句中转换第二个变量

Kotlin supervisorScope 即使包裹在 try catch 中也会失败

协程子作业(job)取消

如何在 Kotlin 中声明一个空数组而不期望 null?

从 HashMap 检索时的 NPE,即使 containsKey() 在多线程环境中返回 true

如何创建 Kotlin DSL - DSL 语法 Kotlin

使用最新的 com.jakewharton.rxbinding3:rxbinding:3.0.0-alpha2 库时未找到 RxTextView 和其他小部件

如何在调试中修复 ClassNotFoundException: kotlinx.coroutines.debug.AgentPremain?

Kotlin 枚举中的循环引用

API 'variant.getJavaCompile()' 已过时

如何在主线程上使用 Kotlin 协程 await()

将协同路由调用放在存储库或ViewModel中哪个更好?

Kotlin内联扩展属性

如何解决:将Java类转换为Kotlin后出现error: cannot find symbol class ...?

类型不匹配:推断类型为 LoginActivity 但应为 LifecycleOwner

Android Jetpack导航,另一个主机片段中的主机片段

Kotlin - 错误:Could not find or load main class _DefaultPackage

Android Compose 生产准备好了吗?