Putting Elements in MutableList of Kotlin

1.6k views Asked by At
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.

1

There are 1 answers

0
Jolan DAUMAS On BEST ANSWER

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)
}