java 如何在 Kotlin 中将 intArray 转换为 ArrayList<Int>?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40036160/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert intArray to ArrayList<Int> in Kotlin?
提问by UmAnusorn
From
从
val array = intArrayOf(5, 3, 0, 2, 4, 1, 0, 5, 2, 3, 1, 4)
I need to convert to ArrayList<Int>
我需要转换为 ArrayList<Int>
I have tried array.toTypedArray()
我努力了 array.toTypedArray()
But it converted to Array<Int>
instead
但它转换为Array<Int>
替代
回答by Ilya
You can use toCollection
function and specify ArrayList
as a mutable collection to fill:
您可以使用toCollection
函数并指定ArrayList
为可变集合来填充:
val arrayList = intArrayOf(1, 2, 5).toCollection(ArrayList())
回答by miensol
You can get List<Int>
with a simple toList
call like so:
您可以List<Int>
通过如下简单的toList
调用获得:
val list = intArrayOf(5, 3, 0, 2).toList()
However if you really need ArrayList
you can create it too:
但是,如果您确实需要,ArrayList
您也可以创建它:
val list = arrayListOf(*intArrayOf(5, 3, 0, 2).toTypedArray())
or using more idiomatic Kotlin API as suggested by @Ilya:
或者使用@Ilya建议的更惯用的 Kotlin API :
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) } }
}