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.
What does this print?
int[][] ZERO = new int[3][];
ZERO[0] = ZERO[1] = ZERO[2] = new int[] {0, 0, 0};
ZERO[0][1] = 1;
System.out.println(ZERO[2][1]);
Answer: 1
Why: All of the rows are pointing to the same array object. Therefore, when we reassign ZERO[0][1]
, it reassigns all of the row values. Therefore, ZERO[2][1]
prints out 1
.