Home > Enterprise >  How to add a list in list of list in Kotlin?
How to add a list in list of list in Kotlin?

Time:07-28

val myList = mutableListOf<Int>()
    val listOfList = mutableListOf<List<Int>>()
    for (i in 0..2) {
        for (j in 0..2) {
            myList.add(j)
        }
        listOfList.add(myList)
    }
    println(listOfList)

output is

[[0, 1, 2, 0, 1, 2, 0, 1, 2], [0, 1, 2, 0, 1, 2, 0, 1, 2], [0, 1, 2, 0, 1, 2, 0, 1, 2]]

instead of

[[0, 1, 2],[0, 1, 2, 0, 1, 2],[0, 1, 2, 0, 1, 2, 0, 1, 2]]

the final result populates the list with last inner list

CodePudding user response:

Note that in your listOfList.add(myList), myList is the same object for every i. Your myList.add(j) statement will affect the same list every time.
One way around it, is to add a clone (instead of the same object) to listOfList.

fun main() {
    val myList = mutableListOf<Int>()
    val listOfList = mutableListOf<List<Int>>()
    for (i in 0..2) {
        for (j in 0..2) {
            myList.add(j)
        }
        println("mylist -> "   myList)
        listOfList.add(myList.toMutableList()) //add a clone instead of using the same myList object every time
        println("list of lists-> "   listOfList)
    }
    println("final list of lists -> "   listOfList)

}

Output:

mylist -> [0, 1, 2]
list of lists-> [[0, 1, 2]]
mylist -> [0, 1, 2, 0, 1, 2]
list of lists-> [[0, 1, 2], [0, 1, 2, 0, 1, 2]]
mylist -> [0, 1, 2, 0, 1, 2, 0, 1, 2]
list of lists-> [[0, 1, 2], [0, 1, 2, 0, 1, 2], [0, 1, 2, 0, 1, 2, 0, 1, 2]]
final list of lists -> [[0, 1, 2], [0, 1, 2, 0, 1, 2], [0, 1, 2, 0, 1, 2, 0, 1, 2]]
  • Related