Kotlin List – Replace Element at Specific Index
We can modify the contents of a List only if the list is mutable.
To replace an element in a Mutable List at given index in Kotlin, call set()
function on this list object and pass the index and the element as arguments.
The syntax of set() function is
MutableList.set(index, element)
Examples
In the following program, we will create a mutable list with some elements in it. We shall then replace the element at index 3
in this list with the element 0
using set() function.
Main.kt
fun main(args: Array<String>) {
val mutableList: MutableList<Int> = mutableListOf(1, 4, 9, 16, 25)
println("List before replacing : " + mutableList)
mutableList.set(3, 0)
println("List after replacing : " + mutableList)
}
Output
List before replacing : [1, 4, 9, 16, 25]
List after replacing : [1, 4, 9, 0, 25]
If the specified index is out of bounds for this list object, then set() throws java.lang.IndexOutOfBoundsException.
In the following program, we will try to replace the element at index 7
, while the size of this list is 5
.
Main.kt
fun main(args: Array<String>) {
val mutableList: MutableList<Int> = mutableListOf(1, 4, 9, 16, 25)
println("List before replacing : " + mutableList)
mutableList.set(7, 0)
println("List after replacing : " + mutableList)
}
Output
List before replacing : [1, 4, 9, 16, 25]
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 7 out of bounds for length 5
at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248)
at java.base/java.util.Objects.checkIndex(Objects.java:372)
at java.base/java.util.ArrayList.set(ArrayList.java:473)
at MainKt.main(Main.kt:4)
Conclusion
In this Kotlin Tutorial, we learned how to replace an element at specific index, with another element, in a mutable list in Kotlin, using set() function, with the help of example programs.