为什么 MutableList 没有排序函数?

问题描述 投票:0回答:1

Kotlin 的索引集合 List 和 MutableList 可以使用一组函数进行排序,但其中一些函数(如排序())返回一个 List,而不是分别返回 List 和 MutableList。将排序后的 MutableList 转换为函数内的 List,然后如果我们想将其用作函数中的参数,则必须手动将其再次重新转换为 MutableList,这背后的原因是什么?为什么没有一个扩展函数可以做到这一点?

public fun <T : Comparable<T>> MutableList<T>.sorted(): MutableList<T> {
    // sort the Mutable List
}
kotlin sorting extension-methods mutablelist
1个回答
0
投票

因为列表排序的结果可能是不可变的。

...事实上,如果您查看

sorted()
的实现,通常会出现这种情况:

public fun <T : Comparable<T>> Iterable<T>.sorted(): List<T> {
    if (this is Collection) {
        if (size <= 1) return this.toList()
        @Suppress("UNCHECKED_CAST")
        return (toTypedArray<Comparable<T>>() as Array<T>).apply { sort() }.asList()
    }
    return toMutableList().apply { sort() }
}

对于 JVM 上的

Collection
子类,该
.asList()
调用最终会调用
Arrays.asList
,它返回“由指定数组支持的 固定大小 列表”(已添加强调)。

这意味着...

将排序后的 MutableList 转换为函数内的 List,然后我们必须手动将其再次重新转换为 MutableList 的原因是什么

...您无法安全地进行此转换,因为您可能没有

MutableList
(或者至少没有允许长度更改的工具,这可能是您期望
MutableList
允许的)。

相反,你应该这样做:

someMutableList.sorted().toMutableList()

这将保证您得到的是正常的

MutableList

© www.soinside.com 2019 - 2024. All rights reserved.