Even Higher Dimensions

You don't have to stop with two dimensional arrays. Java permits arrays of three, four or more dimensions. However chances are pretty good that if you need more than three dimensions in an array, you're probably using the wrong data structure. Even three dimensional arrays are exceptionally rare outside of scientific and engineering applications.

The syntax for three dimensional arrays is a direct extension of that for two-dimensional arrays. The program below declares, allocates and initializes a three-dimensional array. The array is filled with the sum of its indexes.

class Fill3DArray {

  public static void main (String args[]) {
    int[][][] M;
    M = new int[4][5][3];
    for (int row=0; row < 4; row++) {
      for (int col=0; col < 5; col++) {
        for (int ver=0; ver < 3; ver++) {
          M[row][col][ver] = row+col+ver;

You need the additional nested for loop to handle the extra dimension. The syntax for still higher dimensions is similar. Just add another pair of brackets and another dimension.

Unbalanced Arrays

Like C Java does not have true multidimensional arrays. Java fakes multidimensional arrays using arrays of arrays. This means that it is possible to have unbalanced arrays. An unbalanced array is a multidimensional array where the dimension isn't the same for all rows. In most applications this is a horrible idea and should be avoided.

Previous | Next | Top | Cafe au Lait

Copyright 1997 Elliotte Rusty Harold
Last Modified July 14, 1997