[Changing the code] It's kotlin. How do I modify this code?

Asked 2 years ago, Updated 2 years ago, 66 views

class Snapshot<T>(private val array:MutableList<T>) {

    fun restore():MutableList<T> {
        return array
    }    
}

fun test2(){
    var array = mutableListOf(1,2)
    val snap = Snapshot(array)
    array[0] = 1
    array = snap.restore()
    println(array.toList().joinToString()) //It should log "1,2"
    array.add(4)
    array = snap.restore()
    println(array.toList().joinToString()) //It should log "1,2"
}

fun main(str: Array<String>) {
    test2()
}

//Current state output:
1, 2
1, 2, 4

//Normal output:
1,2
1,2

kotlin algorithm

2022-09-21 13:51

2 Answers

It's a self-answer.

class Snapshot<T>(private val array: MutableList<T>) {
    var deepCopyArray:MutableList<T> = ArrayList()

    init {
        deepCopyArray.addAll(array)
    }

    fun restore():MutableList<T> {
        array.clear()
        array.addAll(deepCopyArray)
        return array
    }
}
fun test2(){
    var array = mutableListOf(1,2)
    val snap = Snapshot(array)
    array[0] = 1
    array = snap.restore()
    println(array.toList().joinToString()) //It should log "1,2"
    array.add(4)
    array = snap.restore()
    println(array.toList().joinToString()) //It should log "1,2"
}

fun main(str: Array<String>) {
    test2()
}

//Current state output:
1, 2
1, 2

//Normal output:
1, 2
1, 2


2022-09-21 13:51

Since it is MutableList and add(4), it is normal to get 1, 2, and 4.

It's more important to understand why it's 1, 2, and 4.

In Cotlin, the collection is divided into changeable and impossible types.

By default, the list you use is add because it is an immutable type or because you explicitly used MutableList.


2022-09-21 13:51

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.