Add a new element at end of an array in Kotlin
This article explores different ways to add a new element at the end of an array in Kotlin.
The arrays in Kotlin are fixed-size. That means once created, we can’t resize them. To get a resizable-array implementation, consider using MutableList instead, which can grow or shrink automatically as needed.
However, if you’re stuck on using arrays, you can create a new array to accommodate the additional element. We can do this in several ways:
1. Using plus() function
A good and concise solution to add an element at the end of an array in Kotlin is with the + operator or the plus() function. We can use this as:
|
1 2 3 4 5 6 7 8 |
fun main() { var nums = arrayOf(1, 2, 3, 4) // add 5 to nums[] nums += 5 // or, nums = nums.plus(5) println(nums.contentToString()) // [1, 2, 3, 4, 5] } |
2. Using MutableList
The trick is to convert the array into a MutableList, add the specified element at the end of the list, and finally return an array containing all the elements in this list.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
fun append(arr: Array<Int>, element: Int): Array<Int> { val list: MutableList<Int> = arr.toMutableList() list.add(element) return list.toTypedArray() } fun main() { var nums = arrayOf(1, 2, 3, 4) nums = append(nums, 5) // add 5 to nums[] println(nums.contentToString()) // [1, 2, 3, 4, 5] } |
3. Using System.arraycopy()
Another idea is to allocate the larger array for accommodating the new element(s). The following solution allocates memory for the new array, one more than the original array’s size. Then it calls the System.arraycopy() function to copy elements from the original array into the new array and finally assign the specified element to the last index of the array.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
fun append(arr: Array<Int?>, element: Int): Array<Int?> { val array = arrayOfNulls<Int>(arr.size + 1) System.arraycopy(arr, 0, array, 0, arr.size) array[arr.size] = element return array } fun main() { var nums = arrayOf<Int?>(1, 2, 3, 4) nums = append(nums, 5) // add 5 to nums[] println(nums.contentToString()) // [1, 2, 3, 4, 5] } |
4. Using Arrays.copyOf()
Instead of using System.arraycopy(), you can also use the copyOf() function, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
fun <T> append(arr: Array<T>, element: T): Array<T?> { val array = arr.copyOf(arr.size + 1) array[arr.size] = element return array } fun main() { var nums = arrayOf<Int?>(1, 2, 3, 4) nums = append(nums, 5) // add 5 to nums[] println(nums.contentToString()) // [1, 2, 3, 4, 5] } |
That’s all about adding a new element at the end of an 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 :)