How to insert an object in an ArrayList at a specific position

后端 未结 7 1163
挽巷
挽巷 2020-11-29 22:08

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

相关标签:
7条回答
  • 2020-11-29 22:47

    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)
        }
    }
    
    0 讨论(0)
提交回复
热议问题