umitems umitems - 1 month ago 18
Java Question

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

Answer

You can get List<Int> with a simple toList call like so:

val list = intArrayOf(5, 3, 0, 2, 4, 1, 0, 5, 2, 3, 1, 4).toList()

However if you really want have ArrayList you can create it too:

val list = arrayListOf(*intArrayOf(5, 3, 0, 2, 4, 1, 0, 5, 2, 3, 1, 4).toTypedArray())

Or if you'd like to save some allocations you can do:

val arrayList: ArrayList<Int> = intArrayOf(5, 3, 0, 2, 4, 1, 0, 5, 2, 3, 1, 4).let { intList ->
    ArrayList<Int>(intList.size).apply { intList.forEach { add(it) } }
}