Suppose I have an ArrayList of objects of size n. Now I want to insert an another object at specific position, let\'s say at index position k (is greater than 0 and less tha
You must handle ArrayIndexOutOfBounds by yourself when adding to a certain position.
For convenience, you may use this extension function in Kotlin
/**
* Adds an [element] to index [index] or to the end of the List in case [index] is out of bounds
*/
fun <T> MutableList<T>.insert(index: Int, element: T) {
if (index <= size) {
add(index, element)
} else {
add(element)
}
}