kotlin - 如何将MutableList添加到其他MutableList-Kotlin?

标签 kotlin mutablelist

下午好,亲爱的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/

相关文章:

android - 如何修复 Required Iterable 但在 Kotlin 中找到了 List

android - Jetpack 撰写 : LazyColumn not updating with MutableList

Scala 2.13用什么代替MutableList?

java - ActiveMQ:拦截发布到某个主题

java - nodejs和kotlin中的SHA256不同哈希

android - Razorpay android SDK集成问题

android - 在 Unix 中显示时间戳,在 Android Kotlin 中显示 UTC

kotlin - 为什么在 Kotlin 中可以从逆变列表中读取

java - viewmodelfactory 和使用 Activity 模块的 View 模型注入(inject)之间的区别