下午好,亲爱的StackOverflow社区,
我在Kotlin中使用MutableList遇到问题。更具体地说,我没有成功在MutableList 内添加MutableList。
例如,后面的例子

fun main() {

    var mutableListIndex: MutableList<Int> = mutableListOf<Int>()
    var mutableListTotal: MutableList<MutableList<Int>> = mutableListOf<MutableList<Int>>()

    for(i in 0..5) {
        mutableListIndex.add(i)
        println(mutableListIndex)

        mutableListTotal.add(mutableListIndex)
        println(mutableListTotal)

    }
}
我得到以下结果
[0]
[[0]]
[0, 1]
[[0, 1], [0, 1]]
[0, 1, 2]
[[0, 1, 2], [0, 1, 2], [0, 1, 2]]
[0, 1, 2, 3]
[[0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]]
[0, 1, 2, 3, 4]
[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]
[0, 1, 2, 3, 4, 5]
[[0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5]]
一会儿,我期待结果
[0]
[[0]]
[0, 1]
[[0], [0, 1]]
[0, 1, 2]
[[0], [0, 1], [0, 1, 2]]
[0, 1, 2, 3]
[[0], [0, 1], [0, 1, 2], [0, 1, 2, 3]]
[0, 1, 2, 3, 4]
[[0], [0, 1], [0, 1, 2], [0, 1, 2, 3], [0, 1, 2, 3, 4]]
[0, 1, 2, 3, 4, 5]
[[0], [0, 1], [0, 1, 2], [0, 1, 2, 3], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4, 5]]

我没有成功理解我错了,因为从严格的算法 Angular 来看,我认为代码是好的。
有人可以帮我解释我的错误吗?
您忠诚的

最佳答案

遵循上面的Animesh Sahu先生的建议,我最终遵循以下解决方案:

fun main() {

    var mutableListIndex: MutableList<Int> = mutableListOf<Int>()
    var mutableListTotal: MutableList<MutableList<Int>> = mutableListOf<MutableList<Int>>()

    for(i in 0..5) {


        mutableListIndex.add(i)
        println(mutableListIndex)


        mutableListTotal.add(mutableListIndex.toMutableList())
        println(mutableListTotal)

    }
}
给出:
[0]
[[0]]
[0, 1]
[[0], [0, 1]]
[0, 1, 2]
[[0], [0, 1], [0, 1, 2]]
[0, 1, 2, 3]
[[0], [0, 1], [0, 1, 2], [0, 1, 2, 3]]
[0, 1, 2, 3, 4]
[[0], [0, 1], [0, 1, 2], [0, 1, 2, 3], [0, 1, 2, 3, 4]]
[0, 1, 2, 3, 4, 5]
[[0], [0, 1], [0, 1, 2], [0, 1, 2, 3], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4, 5]]
非常感谢您的及时答复和帮助
您忠诚的

关于kotlin - 如何将MutableList添加到其他MutableList-Kotlin?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/63073372/

10-09 18:52