AI.
AI.

Reputation: 996

Convert Array<String> to ArrayList<String>

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))

I receive this error:

Error

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

Upvotes: 11

Views: 12689

Answers (5)

Md. Arif
Md. Arif

Reputation: 508

Hope it'll help.

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

Upvotes: 3

ggorlen
ggorlen

Reputation: 56875

The spread operator and arrayListOf is another option:

var categoryList : ArrayList<String>?=null
val list = arrayOf("None", "ABC")
categoryList = arrayListOf(*list)

Upvotes: 0

milon27
milon27

Reputation: 31


import kotlin.collections.ArrayList

var arr:List<String>=["one","two"]<br>
val array_list:ArrayList<String>=ArrayList(arr)


Upvotes: -1

John Joe
John Joe

Reputation: 12803

Another approach is use arrayListOf

 categoryList =arrayListOf("None", "ABC")

Upvotes: 1

Roland
Roland

Reputation: 23242

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

categoryList = list.toCollection(ArrayList())

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))

Upvotes: 20

Related Questions