如何在Kotlin复制列表?

我使用

val selectedSeries = mutableListOf<String>()
selectedSeries.addAll(series)

有没有更简单的方法?


当前回答

我将使用toCollection()扩展方法:

val original = listOf("A", "B", "C")
val copy = original.toCollection(mutableListOf())

这将创建一个新的MutableList,然后将原列表中的每个元素添加到新创建的列表中。

这里的推断类型是MutableList<String>。如果你不想暴露这个新列表的可变性,你可以显式地将该类型声明为一个不可变列表:

val copy: List<String> = original.toCollection(mutableListOf())

其他回答

我将使用toCollection()扩展方法:

val original = listOf("A", "B", "C")
val copy = original.toCollection(mutableListOf())

这将创建一个新的MutableList,然后将原列表中的每个元素添加到新创建的列表中。

这里的推断类型是MutableList<String>。如果你不想暴露这个新列表的可变性,你可以显式地将该类型声明为一个不可变列表:

val copy: List<String> = original.toCollection(mutableListOf())

我建议你做个肤浅的拷贝

.map{it}

这将适用于许多收集类型。

你可以使用

工作表 -> 到列表()

数组 -> toArray()

ArrayList -> toArray()

MutableList -> toMutableList()


例子:

val array = arrayListOf("1", "2", "3", "4")

val arrayCopy = array.toArray() // copy array to other array

Log.i("---> array " ,  array?.count().toString())
Log.i("---> arrayCopy " ,  arrayCopy?.count().toString())

array.removeAt(0) // remove first item in array 

Log.i("---> array after remove" ,  array?.count().toString())
Log.i("---> arrayCopy after remove" ,  arrayCopy?.count().toString())

打印日志:

array: 4
arrayCopy: 4
array after remove: 3
arrayCopy after remove: 4

你可以使用ArrayList构造函数:

You can use the provided extension Iterable.toMutableList() which will provide you with a new list. Unfortunately, as its signature and documentation suggest, it's meant to ensure that an Iterable is a List (just like toString and many other to<type> methods). Nothing guarantees you that it's going to be a new list. For instance, adding the following line at the beginning of the extension: if (this is List) return this is a legitimate performance improvement (if it indeed improves the performance).

另外,由于它的名字,结果代码不是很清楚。

我更喜欢添加我自己的扩展,以确保结果,并创建一个更清晰的代码(就像我们有数组):

fun <T> List<T>.copyOf(): List<T> {
    return mutableListOf<T>().also { it.addAll(this) }
}

fun <T> List<T>.mutableCopyOf(): MutableList<T> {
    return mutableListOf<T>().also { it.addAll(this) }
}

注意,addAll是最快的复制方式,因为它使用本机系统。ArrayList的实现中的arraycopy。

另外,要注意这只会给你一个浅拷贝。

编辑:

你可能想要使用更通用的版本:

fun <T> Collection<T>.copyOf(): Collection<T> {
    return mutableListOf<T>().also { it.addAll(this) }
}

fun <T> Collection<T>.mutableCopyOf(): MutableCollection<T> {
    return mutableListOf<T>().also { it.addAll(this) }
}