51

From

val array = intArrayOf(5, 3, 0, 2, 4, 1, 0, 5, 2, 3, 1, 4)

I need to convert to ArrayList<Int>

I have tried array.toTypedArray()

But it converted to Array<Int> instead

1
  • 1
    It is worth scanning the API references for Kotlin stdlib where you'll find a lot of useful functions such as toList() ... kotlinlang.org/api/latest/jvm/stdlib Commented Oct 14, 2016 at 13:08

3 Answers 3

87

You can use toCollection function and specify ArrayList as a mutable collection to fill:

val arrayList = intArrayOf(1, 2, 5).toCollection(ArrayList())
Sign up to request clarification or add additional context in comments.

3 Comments

this is the intended API
@IgorGanapolsky It should. You can try this code on play.kotlinlang.org: pl.kotl.in/9s_sfYftP
@Ilya how u create short url on kotlin obline compiler?
22

You can get List<Int> with a simple toList call like so:

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

However if you really need ArrayList you can create it too:

val list = arrayListOf(*intArrayOf(5, 3, 0, 2).toTypedArray())

or using more idiomatic Kotlin API as suggested by @Ilya:

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

1 Comment

please see the @ilya's answer for idiomatic API usage
0

In Kotlin, you can easily convert intArray to ArrayList<Int> using .toList() function and unsafe cast operator as:

val intArray = intArrayOf(51, 42, 33, 24, 15)

val arrayList: ArrayList<Int> = intArray.toList() as ArrayList<Int>

println(arrayList::class.simpleName)              // ArrayList

println(arrayList)                                // [51, 42, 33, 24, 15]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.