gpt4 book ai didi

Kotlin MutableList 初始容量

转载 作者:行者123 更新时间:2023-12-02 12:23:31 28 4
gpt4 key购买 nike

我正在创建一个值列表,在这种情况下,尽管值一次添加一个,但最终数字是预先知道的。这是在一个将被多次调用的函数中,所以它运行得越快越好。

在 Java 中,我将使用指定初始容量的 ArrayList 构造函数,因为理论上这会使其稍微快一些,因为它避免了调整大小。

在 Kotlin 中,通常使用 mutableListOf(),但这不允许初始容量;从理论上讲,这应该会导致代码稍微慢一些。

在这种情况下是推荐的/惯用的 Kotlin 解决方案:

  • 继续使用 ArrayList 构造函数; ArrayList 是一个完全有效的 MutableList。
  • 忽略这个问题;初始容量实际上从未对速度产生可测量的差异。
  • 还有什么?
  • 最佳答案

    更新答案
    我实际上对容量和大小感到困惑。目前在 Kotlin stdlib 中没有使用默认容量 MutableList 的实现。
    你可以自己制作一个。

    fun <T> mutableListWithCapacity(capacity: Int): MutableList<T> =
    ArrayList(capacity)

    // creates a MutableList of Int with capacity of 5.
    val mutableList = mutableListWithCapacity<Int>(5)
    过时的答案
    原因之一 mutableListOf不允许默认容量是因为 kotlin 中的默认值不为空。
    然而,有一个效用函数 定义 kotlin.collections包裹。
    public inline fun <T> MutableList(size: Int, init: (index: Int) -> T): MutableList<T> {
    val list = ArrayList<T>(size)
    repeat(size) { index -> list.add(init(index)) }
    return list
    }
    您可以使用 List 创建一个列表函数或 MutableList具有默认容量及其映射的函数。
    // creates a list of ints with default capacity of 10 and having nulls.
    // But I highly doubt you should initialize it with a null since Kotlin is a null-safe language.
    val list = MutableList<Int?>(10) { null }
    但是由于 Kotlin 中不应该有空值,如果它打算使用非空列表,否则你必须使用像 ?. 这样的运算符进行空检查。 !!. .

    关于Kotlin MutableList 初始容量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61698098/

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