rpivovar
rpivovar

Reputation: 3438

how to declare an array of mutable lists and populate lists with starting values

I want to create an array of mutable lists, and each mutable list should have a specified number of ints. These ints should have a starting value of 0.

Example: I know the number of mutable lists, n, in the array, and I know how many integers, m are in each list. I think I can declare the array like so:

// represents number of mutable lists in the array
val n = 2
// represents number of Ints inside each mutable list
val m = 3

val arr = Array<MutableList<Int>>(n) { ??? }

What this should do is it should create an Array arr that contains only the type MutableList. The array is of size n. The mutable lists take in only the type Int.

I am not sure how to iterate through these mutable lists and add m number of 0 valued integers.

Upvotes: 0

Views: 59

Answers (1)

IR42
IR42

Reputation: 9672

Array (size: Int, init: (Int) -> T)

The function init is called for each array element sequentially starting from the first one. It should return the value for an array element given its index.

Same for MutableList

// represents number of mutable lists in the array
val n = 2
// represents number of Ints inside each mutable list
val m = 3

val arr = Array(n) { MutableList(m) { 0 } }

Upvotes: 1

Related Questions