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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 04:52:31  来源:igfitidea点击:

How to convert intArray to ArrayList<Int> in Kotlin?

javakotlin

提问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 toCollectionfunction and specify ArrayListas 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 toListcall like so:

您可以List<Int>通过如下简单的toList调用获得:

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

However if you really need ArrayListyou 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) } }
}