Nice programing

Kotlin에서 목록을 복제하거나 복사하는 방법

nicepro 2020. 11. 14. 11:08
반응형

Kotlin에서 목록을 복제하거나 복사하는 방법


Kotlin에서 목록을 복사하는 방법은 무엇입니까?

나는 사용하고있다

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

더 쉬운 방법이 있습니까?


이것은 잘 작동합니다.

val selectedSeries = series.toMutableList()

두 가지 대안을 생각해 낼 수 있습니다.

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.kt명령 줄 또는 kotlin { experimental { newInference 'enable'}Gradle입니다. 새로운 유형 추론에 대한 자세한 내용은 KotlinConf 2018-Svetlana Isakova의 새로운 유형 추론 및 관련 언어 기능 , 특히 '빌더를위한 추론 '30 ' 동영상을 확인하세요.


당신이 사용할 수있는

목록-> toList ()

배열-> 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 데이터 클래스가있는 경우 다음을 수행 할 수 있습니다.

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

얕은 사본의 경우

.map{it}

이는 많은 컬렉션 유형에서 작동합니다.


확장 방법을 사용 합니다toCollection() .

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

그러면 새로 생성 된 MutableList다음 원본의 각 요소가 새로 생성 된 목록에 추가됩니다.

여기서 추론 된 유형은입니다 MutableList<String>. 이 새 목록의 변경 가능성을 노출하지 않으려면 유형을 변경 불가능한 목록으로 명시 적으로 선언 할 수 있습니다.

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

Java에서와 같이 :

명부:

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

지도:

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

JVM을 목표로한다고 가정합니다. ArrayList 및 HashMap의 복사 생성자에 의존하기 때문에 다른 대상에서 작동하는지 확실하지 않습니다.


간단한 목록의 경우 위에 올바른 솔루션이 많이 있습니다.

그러나 그것은 단지 얕은 목록을위한 것입니다.

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

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

참고URL : https://stackoverflow.com/questions/46846025/how-to-clone-or-copy-a-list-in-kotlin

반응형