English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Kotlin Program to Merge Two Arrays

Comprehensive Collection of Kotlin Examples

In this program, you will learn to connect two arrays in Kotlin using arraycopy and without using arraycopy.

Example1: Using arraycopy to connect two arrays

import java.util.Arrays
fun main(args: Array<String>) {
    val array1 = intArrayOf(1, 2, 3)
    val array2 = intArrayOf(4, 5, 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))
}

When running the program, the output is:

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

In the above program, we have two integer arrays array1and array2.

To merge (concatenate) two arrays, we find their lengths stored in aLen and bLen, respectively. Then, we create an array of length aLen + bLen's new integer array result.

Now, in order to combine the two, we use the arraycopy() function to copy each element of the two arrays to result.

arraycopy(array1, 0, result, 0, aLen) function, simply put, the program will copy array1Copy from index 0 to result and from index 0 to aLen.

Similarly, for arraycopy(array2, 0, result, aLen, bLen) tells the program to copy array2Copy from index 0 to result and from index aLen to bLen.

Example2: Concatenating two arrays without using arraycopy

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

When running the program, the output is:

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

In the above program, we did not use arraycopy, but manually copied the array array1and array2each element to result.

We store the total length required for result, which is the length of array1.length + array2. length. Then, we create a new array result with a new length.

Now, we use for-each loop to traverse array1and store it in the result. After assignment, we increase the position pos 1, pos++.

Similarly, we take each element of array2Perform the same operation and start from array1Start storing each element of result from the next position.

This is the equivalent Java code:Java Program to Connect Two Arrays.

Comprehensive Collection of Kotlin Examples