Week 02-1: Values and Containers

Multidimensional Arrays

What if we have something like this:

$$ A = \begin{bmatrix} 1 & 2 & 3 \\ 4 & 5 & 6 \\ 7 & 8 & 9 \end{bmatrix} $$

These are not primitive in Java, but we can make arrays of arrays!


int[][] A = new int[3][];
A[0] = new int[] {1, 2, 3};
A[1] = new int[] {4, 5, 6};
A[2] = new int[] {7, 8, 9};

// or
int[][] A = { {1, 2, 3},
              {4, 5, 6},
              {7, 8, 9} };

We can reference the individual objects using A[row][col].

Exotic Multidimensional Arrays

Since every element of an array is independent, we don’t need to have a fixed “width”, giving a “ragged” array.