How can I convert:
mutableListOf<MutableList<Pair<Int, Int>>>
To a:
Array<Array<Pair<Int,Int>>>
I’m pretty new in the language of Kotlin, I thought that I can loop for the entire 2D array and put the values in the new one, but I was wondering if there’s another faster solution
>Solution :
I thought that I can loop for the entire 2D array and put the values in the new one
You can’t actually explicitly "loop". When you create an Array
of non-null elements in Kotlin you have to specify the default value at each index. So all you have to do is specify each element of the list:
// suppose list is a MutableList<MutableList<Pair<Int, Int>>>
// create an array of list.size...
Array(list.size) { i ->
// where the element at index i is another array with size "list[i].size"
Array(list[i].size) { j ->
// and the element at index j of this array is "list[i][j]"
list[i][j]
}
}
This is pretty much as fast as you can get in terms of execution time.
If you mean "fast" as in less typing, you can do:
list.map { it.toTypedArray() }.toTypedArray()
This first converts the inner lists to arrays, creating a List<Array<Pair<Int, Int>>>
, and then converts that list to an array.