list 如何在 kotlin 中克隆或复制列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46846025/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 08:14:26  来源:igfitidea点击:

How to clone or copy a list in kotlin

listcopykotlin

提问by Audi

How to copy list in Kotlin?

如何在 Kotlin 中复制列表?

I'm using

我正在使用

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

Is there a easier way?

有没有更简单的方法?

回答by Audi

This works fine.

这工作正常。

val selectedSeries = series.toMutableList()

回答by Rasoul Miri

You can use

您可以使用

List -> toList()

列表 -> toList()

Array -> toArray()

数组 -> toArray()

ArrayList -> toArray()

ArrayList -> toArray()

MutableList -> toMutableList()

MutableList -> toMutableList()



Example:

例子:

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())

print log:

打印日志:

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

回答by Jacob Wu

I can come up with two alternative ways:

我可以想出两种替代方法:

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

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

Update: with the new Type Inference engine(opt-in in Kotlin 1.3), We can omit the generic type parameter in 1st example and have this:

更新:使用新的类型推断引擎(在 Kotlin 1.3 中选择加入),我们可以省略第一个示例中的泛型类型参数并具有以下内容:

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

FYI.The way to opt-in new Inference is kotlinc -Xnew-inference ./SourceCode.ktfor command line, or kotlin { experimental { newInference 'enable'}for Gradle. For more info about the new Type Inference, check this video: KotlinConf 2018 - New Type Inference and Related Language Features by Svetlana Isakova, especially 'inference for builders' at 30'

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

回答by Levon Petrosyan

If your list is holding kotlin data class, you can do this

如果您的列表包含kotlin 数据类,则可以执行此操作

selectedSeries = ArrayList(series.map { it.copy() })

回答by Sir Codesalot

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

您可以使用提供的扩展程序Iterable.toMutableList(),它将为您提供一个新列表。不幸的是,正如它的签名和文档所暗示的那样,它旨在确保 anIterable是一个List(就像toString许多其他to<type>方法一样)。没有什么可以保证它会是一个列表。例如,在扩展的开头添加以下行:if (this is List) return this是合法的性能改进(如果它确实提高了性能)。

Also, because of its name, the resulting code isn't very clear.

此外,由于它的名称,生成的代码不是很清楚。

I prefer to add my own extension to be sure of the result and create a much more clear code (just like we have for arrays):

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

fun <T> List<T>.copyOf(): List<T> {
    val original = this
    return mutableListOf<T>().apply { addAll(original) }
}

fun <T> List<T>.mutableCopyOf(): MutableList<T> {
    val original = this
    return mutableListOf<T>().apply { addAll(original) }
}

Note that addAllis the fastest way to copy because it uses the native System.arraycopyin the implementation of ArrayList.

请注意,这addAll是最快的复制方式,因为它System.arraycopyArrayList.

Also, beware that this will only give you a shallow copy.

另外,请注意,这只会给您一个浅拷贝

回答by Lensflare

For a shallow copy, I suggest

对于浅拷贝,我建议

.map{it}

That will work for many collection types.

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

回答by noamtm

Just like in Java:

就像在 Java 中一样:

List:

列表:

    val list = mutableListOf("a", "b", "c")
    val list2 = ArrayList(list)

Map:

地图:

    val map = mutableMapOf("a" to 1, "b" to 2, "c" to 3)
    val map2 = HashMap(map)

Assuming you're targeting the JVM (or Android); I'm not sure it works for other targets, as it relies on the copy constructors of ArrayList and HashMap.

假设您的目标是 JVM(或 Android);我不确定它是否适用于其他目标,因为它依赖于 ArrayList 和 HashMap 的复制构造函数。

回答by Ben P.

I would use the toCollection()extension method:

我会使用toCollection()扩展方法

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

This will create a new MutableListand then add each element of the original to the newly-created list.

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

The inferred type here will be MutableList<String>. If you don't want to expose the mutability of this new list, you can declare the type explicitly as an immutable list:

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

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

回答by Paulo Buchsbaum

For simple lists has many right solutions above.

对于简单的列表,上面有很多正确的解决方案。

However, it's just for shallows lists.

但是,它仅适用于浅表列表。

The below function works for any 2 dimensional ArrayList. ArrayListis, in practice, equivalent to MutableList. Interestingly it doesn't work when using explicit MutableListtype. If one needs more dimensions, it's necessary make more functions.

下面的函数适用于任何二维ArrayListArrayList在实践中,相当于MutableList。有趣的是,它在使用显式MutableList类型时不起作用。如果需要更多的维度,就需要制作更多的功能。

fun <T>cloneMatrix(v:ArrayList<ArrayList<T>>):ArrayList<ArrayList<T>>{
  var MatrResult = ArrayList<ArrayList<T>>()
  for (i in v.indices) MatrResult.add(v[i].clone() as ArrayList<T>)
  return MatrResult
}

Demo for integer Matrix:

整数矩阵的演示:

var mat = arrayListOf(arrayListOf<Int>(1,2),arrayListOf<Int>(3,12))
var mat2 = ArrayList<ArrayList<Int>>()
mat2 = cloneMatrix<Int>(mat)
mat2[1][1]=5
println(mat[1][1])

it shows 12

表明 12

回答by Solomon Ucko

You can use the ArrayListconstructor: ArrayList(list)

您可以使用ArrayList构造函数:ArrayList(list)