Skip to main content

How to convert an ArrayList to an array and Array to ArrayList in Kotlin

How to convert an ArrayList to an array and Array to ArrayList in Kotlin.

Here's a step-by-step tutorial on how to convert an ArrayList to an array and an array to an ArrayList in Kotlin.

Converting an ArrayList to an Array

To convert an ArrayList to an array in Kotlin, you can use the toTypedArray() function. Here's how you can do it:

  1. Declare and initialize an ArrayList with some elements:
val arrayList = ArrayList<String>()
arrayList.add("Apple")
arrayList.add("Banana")
arrayList.add("Orange")
  1. Convert the ArrayList to an array using the toTypedArray() function:
val array = arrayList.toTypedArray()

That's it! Now, the array variable will contain the elements of the ArrayList.

Here's the complete code:

val arrayList = ArrayList<String>()
arrayList.add("Apple")
arrayList.add("Banana")
arrayList.add("Orange")

val array = arrayList.toTypedArray()

Converting an Array to an ArrayList

To convert an array to an ArrayList in Kotlin, you can use the ArrayList constructor that takes an array as its parameter. Here's how you can do it:

  1. Declare and initialize an array with some elements:
val array = arrayOf("Apple", "Banana", "Orange")
  1. Convert the array to an ArrayList using the ArrayList constructor:
val arrayList = ArrayList<String>(array.asList())

That's it! Now, the arrayList variable will contain the elements of the array.

Here's the complete code:

val array = arrayOf("Apple", "Banana", "Orange")

val arrayList = ArrayList<String>(array.asList())

Conclusion

In this tutorial, you learned how to convert an ArrayList to an array and an array to an ArrayList in Kotlin. Converting an ArrayList to an array can be done using the toTypedArray() function, while converting an array to an ArrayList can be done using the ArrayList constructor that takes an array as its parameter.