Copy all elements of an int array into a new array in Kotlin
This article explores different ways to copy all elements of an int array into a new array in Kotlin.
1. Using copyOf() function
The copyOf() function returns a new array, a copy of the original array, resized to the given size. To copy the complete array, pass the original array’s length to the copyOf() function.
|
1 2 3 4 5 6 7 8 9 10 11 |
fun copyArray(source: IntArray): IntArray { return source.copyOf(source.size) } fun main() { val A = intArrayOf(1, 2, 3, 4, 5) val copy = copyArray(A) println(copy.contentToString()) // [1, 2, 3, 4, 5] } |
2. Using copyOfRange() function
The copyOfRange() function is similar to the copyOf() function, but instead of copying elements from the beginning of the array, it copies the elements within the specified range. To copy the whole array, pass the starting index as 0 and ending index equal to the array’s length to the copyOfRange() function.
|
1 2 3 4 5 6 7 8 9 10 11 |
fun copyArray(source: IntArray): IntArray { return source.copyOfRange(0, source.size) } fun main() { val A = intArrayOf(1, 2, 3, 4, 5) val copy = copyArray(A) println(copy.contentToString()) // [1, 2, 3, 4, 5] } |
3. Using clone() function
Alternatively, you can use the extension function clone() for copying arrays.
|
1 2 3 4 5 6 7 8 9 10 11 |
fun copyArray(source: IntArray): IntArray { return source.clone() } fun main() { val A = intArrayOf(1, 2, 3, 4, 5) val copy = copyArray(A) println(copy.contentToString()) // [1, 2, 3, 4, 5] } |
4. Using System.arraycopy() function
Another plausible way is to use the System.arraycopy() function for copying the array, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
fun copyArray(source: IntArray): IntArray { val dest = IntArray(source.size) System.arraycopy(source, 0, dest, 0, source.size) return dest } fun main() { val A = intArrayOf(1, 2, 3, 4, 5) val copy = copyArray(A) println(copy.contentToString()) // [1, 2, 3, 4, 5] } |
5. Using for loop
Finally, you can use a for-loop to copy elements from the source array to the destination array.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
fun copyArray(source: IntArray): IntArray { val n = source.size val dest = IntArray(n) for (i in 0 until n) { dest[i] = source[i] } return dest } fun main() { val A = intArrayOf(1, 2, 3, 4, 5) val copy = copyArray(A) println(copy.contentToString()) // [1, 2, 3, 4, 5] } |
That’s all about copying all elements of an int array into a new array in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)