【发布时间】:2020-11-14 07:23:25
【问题描述】:
下午好,亲爱的 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]]
我无法理解我错在哪里,因为在我看来,从严格的算法角度来看,代码是好的。
有人可以帮我解释一下我的错误吗?
真诚的
【问题讨论】:
-
mutableListIndex正在发生变异,它是堆中的单个对象,对它的更改会反映在mutableListTotal列表中。 -
亲爱的 Animesh Sahu,我明白你的意思。您知道防止这种现象发生的解决方案吗?
-
创建一个新列表并添加它,
mutableListTotal.add(mutableListIndex.toList())toList() 或 toMutableList() 浅拷贝列表的内容并使用它们创建一个新列表。
标签: kotlin mutablelist