我正在创建一个值列表,在这样的情况下,虽然每次都添加一个值,但最终的数字是预先知道的。这是一个将被多次调用的函数,因此它运行得越快,效果就越好。
在Java中,我将使用指定初始容量的ArrayList构造函数,因为从理论上讲,这使其速度稍微快一些,因为它避免了调整大小。
在Kotlin中,人们通常使用mutableListOf(),但这不允许初始容量;理论上,这应该会导致代码稍慢一些。
在本例中,推荐的/惯用的Kotlin解决方案是:
发布于 2020-05-09 14:34:08
更新答复
我实际上被能力和尺寸搞混了。目前Kotlin中没有使用默认容量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中的默认值不是null。
然而,在包中有一个实用函数定义了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
}您可以创建一个具有默认容量的列表函数或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中不应该有空值,如果它打算使用非空列表,那么您必须使用?. !!.这样的操作符进行空检查。
发布于 2020-12-31 09:03:03
填写不可变的列表
val doubles = List(5) { i -> i * 2 }
result --> [0, 2, 4, 6, 8]用零填充由五个元素组成的可变列表
val ints = MutableList(5) { 0 }
result --> [0, 0, 0, 0, 0]发布于 2021-05-09 02:23:30
可以将此mutableList()预定义函数封装在如下函数中
fun <E> emptyMutableList(size: Int = 0): MutableList<E?> {
return MutableList(size) {
null
}
}这将返回大小为MutableList的size,但也会将null分配给其所有单元格。现在,如果您想访问任何索引值,您的程序就不会像在接受的答案中使用解决方案那样与java.lang.IndexOutOfBoundsException崩溃。我的意思是:
fun <E> emptyMutableList(size: Int = 0): MutableList<E?> {
return MutableList(size) {
null
}
}
fun <T> mutableListWithCapacity(capacity: Int): MutableList<T> =
ArrayList(capacity)
fun main() {
val mutableList1 = mutableListWithCapacity<Int>(20)
val mutableList2 = emptyMutableList<Int>(20)
mutableList1[10] // this will throw a java.lang.IndexOutOfBoundsException
mutableList2[10] // this will not throw an exception but it will return null
}当然,一切都取决于你想要的程序的内存效率和无崩溃的程度。
编码愉快!
https://stackoverflow.com/questions/61698098
复制相似问题