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
You can use toCollection function and specify ArrayList as a mutable collection to fill:
val arrayList = intArrayOf(1, 2, 5).toCollection(ArrayList())
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) } }
}
In Kotlin, you can easily convert intArray to ArrayList<Int> using .toList() function and unsafe cast operator as:
val intArray = intArrayOf(51, 42, 33, 24, 15)
val arrayList: ArrayList<Int> = intArray.toList() as ArrayList<Int>
println(arrayList::class.simpleName) // ArrayList
println(arrayList) // [51, 42, 33, 24, 15]
toList()... kotlinlang.org/api/latest/jvm/stdlib