I want to know how to make a resizeable two-dimensional array in Kotlin.
C++ example: vector< vector<int> > my_vector
What I've tried: var seqList: List<List<Int>> = ArrayList<ArrayList<Int>>()
but I'm getting an error when using seqList.add()
error: unresolved reference: add
I have read some questions regarding 2d arrays in Kotlin at stackoverflow, but they are about not-resizeable arrays or are outdated
Because of the possibility of other variables immediately after the array data, you have to allocate a new array with the desired size and copy all the elements from the old array to the new one.
Like the one-dimensional arrays, two-dimensional arrays may be initialized by following their declaration with a list of initial values enclosed in braces. Ex: int a[2][3]={0,0,0,1,1,1}; initializes the elements of the first row to zero and the second row to one. The initialization is done row by row.
Kotlin has separate List
and MutableList
interfaces, as explained here, for example. ArrayList
is a MutableList
, you just have to save it as a MutableList
variable in order to be able to access methods that mutate it:
val seqList: MutableList<MutableList<Int>> = ArrayList() // alternatively: = mutableListOf()
seqList.add(mutableListOf<Int>(1, 2, 3))
Also note the mutableListOf
and arrayListOf
methods in the standard library, which are handy for creating lists instead of directly using the constructor of, say, ArrayList
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With