Kotlin List – Add Element at Specific Index

To add an element to a Mutable List at specific index in Kotlin, we can use add(index, element) function.

add(index, element) adds the element to this Mutable List at given index.

Examples

In the following program, we will create a Mutable List with some integers, and then add an element 88 at index 2, using add(element, index) function.

Main.kt

fun main(args: Array<String>) {
    val mutableList = mutableListOf(1, 3, 9, 16, 25)
    mutableList.add(2, 88)
    println(mutableList)
}

Output

[1, 3, 88, 9, 16, 25]

If the index is greater than the size of the list, then add() function throws java.lang.IndexOutOfBoundsException.

In the following program, the size of the list is five, but let us try to add the element at index 7.

Main.kt

fun main(args: Array<String>) {
    val mutableList = mutableListOf(1, 3, 9, 16, 25)
    mutableList.add(7, 88)
    println(mutableList)
}

Output

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 7, Size: 5
	at java.base/java.util.ArrayList.rangeCheckForAdd(ArrayList.java:788)
	at java.base/java.util.ArrayList.add(ArrayList.java:513)
	at MainKt.main(Main.kt:3)
ADVERTISEMENT

Conclusion

In this Kotlin Tutorial, we learned how to add an element at given index to a mutable list in Kotlin, using add() function, with the help of example programs.