How to clone or copy a list in kotlin

2019-01-26 03:20发布

问题:

How to copy list in Kotlin?

I'm using

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

Is there a easier way?

回答1:

This works fine.

val selectedSeries = series.toMutableList()


回答2:

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:

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

FYI.The way to opt-in new Inference is kotlinc -Xnew-inference ./SourceCode.kt for 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'



回答3:

For a shallow copy, I suggest

.map{it}

That will work for many collection types.



回答4:

I tried this:

    val a = mutableListOf(1, 2, 3)
    val b = listOf(a)
    val c = b.toMutableList()
    c[0][0] = 6
    print("b = $b[0]")
    print("c = $c[0]")

both prints will show 6, so be careful here, it doesn't seem to make a copy!

I also tried it with a data class, same result when changing a member of it this way.



回答5:

You can use

List -> toList()

Array -> toArray()

ArrayList -> toArray()

MutableList -> toMutableList()


Example:

val array:ArrayList<String> = ArrayList()
array.add("1")
array.add("2")
array.add("3")
array.add("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


标签: list copy kotlin