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.
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 :
Or without using index parameter :
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: