如何在Kotlin复制列表?

我使用

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

有没有更简单的方法?


当前回答

你可以使用ArrayList构造函数:

其他回答

var oldList: List<ClassA>?
val newList = oldList.map { it.copy() }

这很好。

val selectedSeries = series.toMutableList()

I can come up with two alternative ways:

1. val selectedSeries = mutableListOf<String>().apply { addAll(series) }

2. val selectedSeries = mutableListOf(*series.toTypedArray())

更新:使用新的类型推断引擎(在Kotlin 1.3中可选),我们可以省略第一个例子中的泛型类型参数,并得到:

1. val selectedSeries = mutableListOf().apply { addAll(series) }

仅供参考。选择新推理的方法是kotlinc -Xnew-inference ./SourceCode。对于命令行,或者对于Gradle, kotlin {experimental {newInference 'enable'}。有关新的类型推断的更多信息,请查看此视频:KotlinConf 2018 -新的类型推断和相关语言特性,作者:Svetlana Isakova,特别是“30岁的构建器推理”

你可以使用

工作表 -> 到列表()

数组 -> 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

试试下面的代码复制列表在Kotlin

arrayList2.addAll(arrayList1.filterNotNull())