Good afternoon dear StackOverflow community,
I encounter a problem using MutableList in Kotlin. More specifically, I do not succeed to add a MutableList inside a MutableList.
For instance, with the example thereafter
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)
}
}
I get the following result
[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]]
While, I am expecting the result thereafter
[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]]
I do not succeed to understand where I am wrong as in my opinion the code from the stricly speaking algorythm point of view is good.
Can someone help and explain me my error ?
Yours faithfully
You always pass in the same reference of
mutableListIndex
to be added intomutableListTotal
. So on every position you have the same object.Then you add a new item into your first list and every reference to it points to the updated List, with one more item.
To get an independent object, that is not updated every time your first reference is updated, you first need to create a copy of the List and only add the copy into your second list. This way an update to your initial list will not be reflected into your copies of the first list.