20. Multidimensional Arrays

Key concepts

  1. Two Dimensional Arrays
  2. Multi-Dimensional Arrays

Introduction

Arrays give us a linear, one-dimensional sequence of data. We may want, however, to represent to two dimensional grid of data. For instance, suppose we want to represent a multiplication table for numbers between 0 and 5. We can get this effect by using an array whose elements are themselves arrays.

Creating a 2D Array

We can create a two dimensional array as follows:
int[][] products = new int[6][6];
The type of products is an array of an array of integers. We can visualize it as follows:

Notice that the name products refers to an array. That array is an array of arrays of integers. products[0] refers to the first array of integers. We'll often talk about two dimensional arrays in terms of rows and columns. The first dimension selects the row -- products[0] selects the array that is the first row. Here are some examples of getting and setting values in the array:

int[][] products = new int[6][6];

int[] secondRow = products[1];         // the second row
secondRow[0] = 0;                      // set some values
secondRow[1] = 1;
secondRow[2] = 2;

// This is legal shorthand: set the 4th element of the 3rd row
products[3][4] = 12;  
Again, we will often use loops to visit all of the elements in our array. Because each row is really another array, we will usually nest our loops in order to visit each element. The outer loop visits every row, and the inner loop visits every column element in the current row.
for (int row=0; row<6; row++) {      // visit each row
  for (int col=0; col<6; col++) {    // visit each column of the current row
    products[row][col] = row*col;
  }
}
Again, we can rewrite this loop to be more resilient in the face of changes to the dimensions of our array, by using the length field of our array:
for (int row=0; row < products.length; row++) {     
  for (int col=0; col < products[row].length; col++) { 
    products[row][col] = row*col;
  }
}
Finally, it's worth pointing out that there are no limits to the number of dimensions our arrays have. A weather application that models temperature in the atmosphere must be able represent three dimensions (essentially latitude, longitude, and altitude). We can create an array to represent this data as follows:
double[][][] temperatures[150][100][120];
The above fragment creates a three dimensional array which we can think of as 150 two dimensional arrays, each of which is 100 one-dimensional arrays of length 120.
Ben Dugan & UW-CSE, Copyright (c) 2001.