next up previous index
Next: Array Access and Memory Up: Arrays of Objects Previous: Arrays of Objects   Index


Multi-Dimensional Arrays

The elements of an array can themselves be arrays. This is a special case of having arrays of Objects. But in this case the original array is said to be a multidimensional array. The following example declares and creates a rectangular integer array with 10 rows and 20 columns:
int a[][] = new int[10][20];
It can be initialised by code such as
for (int i = 0; i < a.length; i++) {
    for (int j = 0; j < a[i].length; j++) {
        a[i][j] = 0;
    }
}
The elements are accessed as a[i][j]. This is a consistent notation since a[i][j] is element j of the array a[i]. This element is said to be in row i and column j. Note that a.length has the value 10 and each a[i].length has the value 20.

Two-dimensional arrays can, of course, be square e.g.

int a[][] = new int[10][10];
They can also have different numbers of columns in each row. For example, the following code declares a (lower) triangular array in which row a[i] has i+1 elements.
int a[][] = new int[10][];
for (int i = 0; i < a.length; i++) {
    a[i] = new int[i+1];
}
Such arrays can be useful for representing symmetric matrices, a[i][j] == a[j][i], where it is only necessary to operate on, and store, one copy of the off-diagonal elements. The following code initialises such an array to the unit matrix, with 1's on the diagonal and 0's elsewhere:
for (int i = 0; i < a.length; i++) {
    for (int j = 0; j < i; j++) {
        a[i][j] = 0;
    }
    a[i][i] = 1;
}
The result is
1 
0 1
0 0 1
if a.length == 3.

Multi-dimensional arrays can also be created and initialised using initialiser lists as in

int a[][] = {{54, 64}, {98, 12, 67}};


next up previous index
Next: Array Access and Memory Up: Arrays of Objects Previous: Arrays of Objects   Index
Peter Williams 2005-06-07