Concatenate Two Arrays in Kotlin

thumbnail

Today, we will learn to concatenate two arrays in Kotlin with arraycopy and without arraycopy. We will create two integer arrays with name array1 and array2. We have to find the length each arrays stored in aLen and bLen, respectively. Then, we create a new integer array result with length aLen + bLen. Now, in order to combine to both, we copy each elements in both arrays to result by using arraycopy() function. The arraycopy(array1, 0, result, 0 ,aLen) fucntion tells the program to copy array1 starting from index 0 to result from index 0 to aLen. Likewise, for arraycopy(array2, 0, result, aLen, bLen) tells the program to copy array2 starting from index 0 to result 0 from index aLen to bLen.

Example 1: Concatenate Two Arrays using arraycopy function in kotlin

import java.util.Arrays

fun main(args: Array<String>) {
    val array1 = intArrayOf(1, 3, 5)
    val array2 = intArrayOf(2, 4, 6)
    val aLen = array1.size
    val bLen = array2.size
    val result = IntArray(aLen + bLen)
    System.arraycopy(array1, 0, result, 0, aLen)
    System.arraycopy(array2, 0, result, aLen, bLen)
    println(Arrays.toString(result))
}

The output will be:

[1, 3, 5, 2, 4, 6]

In the next example, we will show to you the code to concatenate two arrays without arraycopy function. We will manually copy each element of both arrays that is array1 and array2 to result. We need to store the total length (array1.length+array2.length) from the two arrays into variable length because it required for the result variable. Then, we will be able to create a new array result of the length.

Example 2: Concatenate Two Arrays without using arraycopy function in kotlin

import java.util.Arrays

fun main(args: Array<String>) {
    val array1 = intArrayOf(1, 3, 5)
    val array2 = intArrayOf(2, 4, 6)
    val length = array1.size + array2.size
    val result = IntArray(length)
    var position = 0
    for (element in array1) {
        result[pos] = element
        position ++
    }
    for (element in array2) {
        result[position] = element
        position ++
    }
    println(Arrays.toString(result))
}

The output will be:

[1, 3, 5, 2, 4, 6]

Read More:

Back To Top