Multidimensional Arrays

2-Dimensional Arrays

Suppose we are writing a program to play the board game checkers.

We want to store information about what pieces are in which locations. The most natural way to store it would be to index locations by the row and column. This is easily done with a 2-dimensional array:

To declare a 2-D array (of primitive types):

final int BLANK = 0;  // location empty
final int WHITE = 1;  // white piece
final int BLUE = 2;   // blue piece

int board[][] = new int[8][8]; // create 64 integers
board[0][0] = WHITE; // a white piece in row 0, column 0
board[0][1] = BLANK; // row 0, column 1 is empty
board[6][0] = BLUE; // a blue piece in row 6, column 0

Or use a nested loop to load the entire array full of blanks:

for (int i=0; i < 8; i++)
   for (int j=0; j < 8; j++)
      board[i][j] = BLANK;

A 2-D Array is really an Array of Arrays

Internally, Java stores 2 dimensional arrays as an array of arrays:

int [][] nums = new int[5][4];

The above is really equivalent to a 3-step process:

// create the single reference nums (yellow square)
int [][] nums;

// create the array of references (blue squares)
nums = new int[5][];

// this create the second level of arrays (red squares)
for (int i=0; i < 5 ; i++)
   nums[i] = new int[4]; // create arrays of integers

Note: when you initially declare a 2D array:

Elements of the Array: if nums is a 2D array as shown above,

Array of Objects

A 2D array of objects is an array of an array of references to objects:

// creates the single reference nums (yellow square)
Square [][] board;

// creates the array of references to arrays (blue squares)
board = new Square[2][];

// creates are arrays of references to objects (red squares).
for (int i=0; i < board.length ; i++)
   board[i] = new Square[3]; // create arrays of references to objects

Note: the above instructions can be combined into the instruction:

Square [][] board = new Square[2][3];

However, we still have not created any objects! To create objects, there is no simple way other than with loops:

for (int i=0; i < board.length ; i++)
   for (int j=0; j < board[i].length ; j++)
     board[i][j] = new Square(i,j,color);

See Code for Checkers Program.

Higher Dimensional Arrays

One can create arrays of higher dimension than 2. For example, if we were measuring the temperature in a rectangular volume.

int temperature[][][] = new int[10][20][30];

next lecture