You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin中sortArrayWith源码位置及其comparator使用逻辑查询

Kotlin sortWith 函数与 Comparator 用法说明

1. 为什么找不到sortArrayWith源码

sortArrayWith是Kotlin标准库的内部平台相关实现函数,不会对外暴露公开源码:

  • JVM平台下它最终调用JDK内置的Arrays.sort方法,底层采用双轴快排或TimSort算法
  • JS、Native平台下对应各平台的原生排序实现,属于标准库内部工具函数,不会在通用层源码中出现

2. sortArrayWith如何使用传入的Comparator

排序算法运行过程中,每次需要判断两个元素的先后顺序时,就会调用你传入的Comparator.compare(a, b)方法,根据返回值决定两个元素的顺序:

  • 返回值>0:判定a应该排在b的后方
  • 返回值=0:判定a和b顺序优先级相等,稳定排序场景下会保留二者的原有相对位置
  • 返回值<0:判定a应该排在b的前方

你贴出的sortWith扩展函数源码逻辑很简单:只有当数组长度大于1时才会调用排序逻辑,避免无意义的性能开销:

public actual fun <T> Array<out T>.sortWith(comparator: Comparator<in T>): Unit {
    if (size > 1) sortArrayWith(this, 0, size, comparator)
}

3. 你的示例代码逻辑说明

你给出的示例是对Product数组按价格升序原地排序的实现,代码逻辑完全正确:

// 示例Product数组
val products = arrayOf(Product("iPhone 8 Plus 64G", 850.00),
                        Product("iPhone 8 Plus 256G", 1100.00),
                        Product("Apple iPod touch 16GB", 246.00),
                        Product("Apple iPod Nano 16GB", 234.75),
                        Product("iPad Pro 9.7-inch 32 GB", 474.98),
                        Product("iPad Pro 9.7-inch 128G", 574.99),
                        Product("Apple 42mm Smart Watch", 284.93))

// 传入自定义Comparator按价格升序排序
products.sortWith(object: Comparator<Product>{
    override fun compare(p1: Product, p2: Product): Int = when {
        p1.price > p2.price -> 1
        p1.price == p2.price -> 0
        else -> -1
    }
})

上述代码可以简化为两种更简洁的写法,效果完全一致:

  • 用lambda表达式简化Comparator创建
products.sortWith { p1, p2 -> p1.price.compareTo(p2.price) }
  • 直接使用sortBy扩展函数实现单字段升序排序
products.sortBy { it.price }

内容的提问来源于stack exchange,提问作者ntos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 23:57:00