Two-dimensional Arrays
The arrays we’ve seen so far have been one-dimensional – that is, just a list of elements. We can also create multi-dimensional arrays, which are really just arrays of arrays. For example, a 2- dimensional array could represent a mathematical matrix, where each element has an associated row and column.
Declaration
Here’s how to declare a 2-dimensional array:
type[][] name;Here’s how to allocate space for the array spots:
name = new type[numRows][numCols];This creates a two-dimensional array called name, with numRows rows and numCols columns, that holds
elements of type type. Here’s how to create an array called matrix that holds 5 rows and 10 columns of integers:
int[][] matrix = new int[5][10];Initialization
When we allocate space for an array, all spots are automatically initialized to the default value for the type (which is 0 for integers).
If we want to store different values in our array, we must specify both the row index and the column index. As with single-dimensional arrays, the first row is index 0 and the first column is 0. Here’s how we could set the element at row 2 and column 0 to 6 in our matrix example:
matrix[2][0] = 6;Multiplication table example
If we want to initialize all elements of a two-dimensional array, we need to use a nested for loop. The outer loop will step through each row, and the inner loop will step through each column in that row. Here’s how to use a two-dimensional array to represent a multiplication table (the entry at row i and column j has the value i*j):
//Declare, create space
int[][] multTable = new int[10][10];
//Fill with multiplication values
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
multTable[i][j] = i*j;
}
}Now the array looks like this:
| | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
| 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | | 1 | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | | 2 | 0 | 2 | 4 | 6 | 8 | 10 | 12 | 14 | 16 | 18 | | 3 | 0 | 3 | 6 | 9 | 12 | 15 | 18 | 21 | 24 | 27 | | 4 | 0 | 4 | 8 | 12 | 16 | 20 | 24 | 28 | 32 | 36 | | 5 | 0 | 5 | 10 | 15 | 20 | 25 | 30 | 35 | 40 | 45 | | 6 | 0 | 6 | 12 | 18 | 24 | 30 | 36 | 42 | 48 | 54 | | 7 | 0 | 7 | 14 | 21 | 28 | 35 | 42 | 49 | 56 | 63 | | 8 | 0 | 8 | 16 | 24 | 32 | 40 | 48 | 56 | 64 | 72 | | 9 | 0 | 9 | 18 | 27 | 36 | 45 | 54 | 63 | 72 | 81 |