Multi-dimensional Arrays

Dynamic multi-dimensional arrays #

Arrays of arrays are called multi-dimensional arrays. The elements of all of the arrays that we have defined so far have been written in the source code from left to right. To help us understand the concept of a two-dimensional array, let’s define an array from top to bottom this time:

int[] array = [
               10,
               20,
               30,
               40
              ];

As you remember, most spaces in the source code are used to help with readability and do not change the meaning of the code. The array above could have been defined on a single line and would have the same meaning.
Let’s now replace every element of that array with another array:

/* ... */ array = [
                   [ 10, 11, 12 ], 
                   [ 20, 21, 22 ], 
                   [ 30, 31, 32 ], 
                   [ 40, 41, 42 ]
                  ];

We have replaced elements of type int with elements of type int[]. To make the code conform to the array definition syntax, we must now specify the type of the elements as int[][] instead of int[]:

int[][] array = [
               [ 10, 11, 12 ], 
               [ 20, 21, 22 ], 
               [ 30, 31, 32 ], 
               [ 40, 41, 42 ]
              ];

Such arrays are called two-dimensional arrays because they can be seen as having rows and columns.

Adding elements in a multidimensional array #

Two-dimensional arrays are used the same way as any other array as long as we remember that each element is an array itself and can be used in array operations:

array ~= [ 50, 51 ]; // adds a new element (i.e. a slice) 
array[0] ~= 13; // adds to the first element

The new state of the array:

[[10, 11, 12, 13], [20, 21, 22], [30, 31, 32], [40, 41, 42], [50, 51]]

Get hands-on with 1400+ tech skills courses.