gpt4 book ai didi

arraylist - 将Array 转换为ArrayList

转载 作者:行者123 更新时间:2023-12-02 07:18:04 24 4
gpt4 key购买 nike

如何在Kotlin中将Array<String>转换为ArrayList<String>

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 感兴趣,以便将元素添加到您传递的任何集合中:

categoryList = list.toCollection(ArrayList())

请注意,要解决您的特定问题,您只需要 spread operator ( * )即可。使用 * -fix,它也可以工作:
categoryList = ArrayList(Arrays.asList(*list))

关于arraylist - 将Array <String>转换为ArrayList <String>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55451118/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com