How to convert intArray to ArrayList<Int> in Kotlin?
From
val array = intArrayOf(5, 3, 0, 2, 4, 1, 0, 5, 2, 3, 1, 4)
I need to convert to ArrayList<Int>
I have tried array.toTypedArray()
But it converted to Array<Int>
instead
Solution 1:
You can use toCollection
function and specify ArrayList
as a mutable collection to fill:
val arrayList = intArrayOf(1, 2, 5).toCollection(ArrayList())
Solution 2:
You can get List<Int>
with a simple toList
call like so:
val list = intArrayOf(5, 3, 0, 2).toList()
However if you really need ArrayList
you can create it too:
val list = arrayListOf(*intArrayOf(5, 3, 0, 2).toTypedArray())
or using more idiomatic Kotlin API as suggested by @Ilya:
val arrayList = intArrayOf(1, 2, 5).toCollection(ArrayList())
Or if you'd like to do the above yourself and save some allocations:
val arrayList = intArrayOf(5, 3, 0, 2).let { intList ->
ArrayList<Int>(intList.size).apply { intList.forEach { add(it) } }
}