1. Introduction

Array data structures play a crucial part in our role as software developers every day. Aside from the fact that we use them to store data of any type, we are sometimes faced with situations that require us to modify elements at certain positions in our array.

In this tutorial, we’ll explore various ways to insert an element at a particular position in an array in Kotlin.

2. Using a Simple Loop and a New Array

The first method we’re going to look at is using a loop. We iterate over the array, insert all elements of the source array into the new array, and insert the additional element at the desired position:

@Test
fun `insert array element at specific position using a loop and new array`(){
    val array = arrayOf("one", "three", "four", "five")

    val position = 1
    val element = "two"
    val newArray = Array(array.size + 1) { "" }
    
    for (i in 0 until newArray.size) {
        newArray[i] = array[if(i < position) i else i - 1]
    }
    newArray[position] = element
    
    assertArrayEquals(arrayOf("one", "two", "three", "four", "five"), newArray)
}

We also have a variant of this approach that uses System.arraycopy() instead of the simple for loop:

@Test
fun `insert array element at specific position using system arraycopy() and new array`(){
    val array = arrayOf("one", "three", "four", "five")
    val position = 1
    val element = "two"
    val newArray = Array(array.size + 1) { "" }

    System.arraycopy(array, 0, newArray, 0, position)
    newArray[position] = element
    System.arraycopy(array, position, newArray, position + 1, array.size - position)

    assertArrayEquals(arrayOf("one", "two", "three", "four", "five"), newArray)
}

3. Using the copyOfRange() Method

Kotlin’s copyOfRange() method is another way to insert an element at a particular index position of an array. In brief, it copies elements from a specified range of an array, and it accepts two arguments, the first being the start index and the second being the end index of the range we wish to copy:

@Test
fun `insert array element at specific position using copyOfRange() method`(){
    val array = arrayOf("one", "three", "four", "five")
    val position = 1
    val element = "two"
    val newArray = array.copyOfRange(0, position) + element + array.copyOfRange(position, array.size)
    assertArrayEquals(arrayOf("one", "two", "three", "four", "five"), newArray)
}

4. Using the sliceArray() Method and Plus Operator

We can use the sliceArray() method, which is a Kotlin built-in function, to achieve our goal. It accepts an index range as an argument and returns an array containing elements from the given index range. Therefore, we can use this method together with the plus operator to construct an array that contains the given element at a given index:

fun insertArrayElementUsingSliceMethodAndPlusOperator(array: Array<String>, position: Int, element: String): Array<String> {
    return array.sliceArray(0 until position) +
      element + array.sliceArray(position until array.size)
}

Now, let’s test this method for correctness:

@Test
fun `insert array element at specific position using slice() and plus operator`() {
    val array = arrayOf("one", "three", "four", "five")
    val position = 1
    val element = "two"
    val newArray = insertArrayElementUsingSliceMethodAndPlusOperator(array, position, element)

    assertArrayEquals(arrayOf("one", "two", "three", "four", "five"), newArray)
}

5. Using the MutableList Interface

Kotlin’s mutable list interface gives us the ability to add and remove elements at any position in a list. What’s more, we can conveniently convert the modified list back to an array using the toTypedArray() method:

fun insertArrayElementUsingMutableList(array: Array<String>, position: Int, element: String): Array<String> {
    val mutableList = array.toMutableList()
    mutableList.add(position, element)
    return mutableList.toTypedArray()
}

As usual, we need to ensure that this method performs as expected:

@Test
fun `insert array element at specific position using mutabelist method`() {
    val array = arrayOf("one", "three", "four", "five")
    val position = 1
    val element = "two"
    val newArray = insertArrayElementUsingMutableList(array, position, element)

    assertArrayEquals(arrayOf("one", "two", "three", "four", "five"), newArray)
}

6. Conclusion

In this article, we’ve explored various ways to insert an element at a specific index position of an array. Most of the methods rely on intrinsic Kotlin array features such as copyOfRange() and sliceArray(). We also have interesting approaches that use other data structures, such as lists.

As always, the code samples and relevant test cases pertaining to this article can be found over on GitHub.

Comments are closed on this article!