Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resizeable two-dimensional array in Kotlin

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

like image 387
Misho Tek Avatar asked Nov 18 '17 16:11

Misho Tek


People also ask

How do you increase the size of a 2D array?

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.

How is a two-dimensional array initialized?

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.


1 Answers

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.

like image 189
zsmb13 Avatar answered Nov 01 '22 17:11

zsmb13