转换数组<字符串>到 ArrayList<String> [英] Convert Array&lt;String&gt; to ArrayList&lt;String&gt;

查看:30
本文介绍了转换数组<字符串>到 ArrayList<String>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Kotlin 中将 Array 转换为 ArrayList?

How do I convert Array<String> to ArrayList<String> in Kotlin?

var categoryList : ArrayList<String>?=null
val list = arrayOf("None", "ABC")
categoryList = ArrayList(Arrays.asList(list))

我收到此错误:

错误

Type inference failed. Expected type mismatch: inferred type is kotlin.collections.ArrayList<Array<String>!> /* = java.util.ArrayList<Array<String>!> */ but kotlin.collections.ArrayList<String>? /* = java.util.ArrayList<String>? */ was expected

推荐答案

您可能对 toCollection 将元素添加到您传递的任何集合中:

You may be interested in toCollection to add the elements to any collection you pass:

categoryList = list.toCollection(ArrayList())

请注意,要解决您的具体问题,您只需要 扩展运算符 (*).应用 *-fix 后,它也会起作用:

Note that to fix your specific problem you just need the spread operator (*). With the *-fix applied it would have worked too:

categoryList = ArrayList(Arrays.asList(*list))

这篇关于转换数组<字符串>到 ArrayList<String>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆