Search code examples
kotlinmutablelist

Putting Elements in MutableList of Kotlin


fun main() {
    var list1 = mutableListOf<Any>()
    for(i in 0 until 5) {
        list1.set(i,i)
    }
    println(list1)
}

Above Code Gives Index 0 out of Bound for Length 0. What is the Mistake. How do i put elemnts in the MutableList using Index.


Solution

  • You are using the wrong method here.

    According to the documentation of set :"It replaces the element and add new at given index with specified element."

    Here you declare an empty mutableList. So trying to replace at a certain index will give you an Array Out Of Bounds exception.

    If you want to add a new element you need to use the add method : "It adds the given element to the collection."

    So if we use add method it can be write like this :

    fun main() {
        var list1 = mutableListOf<Any>()
        for(i in 0 until 5) {
            list1.add(i,i)
        }
        println(list1)
    }
    

    Or without using index parameter :

    fun main() {
        var list1 = mutableListOf<Any>()
        for(i in 0 until 5) {
            list1.add(i)
        }
        println(list1)
    }
    

    You can still use the set method (even if it's not the best way) by declaring the initial length of your mutable list like @lukas.j said:

    fun main() {
        var list1 = MutableList<Any>(5) {it}
        for(i in 0 until 5) {
            list1.set(i,i)
        }
        println(list1)
    }