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;
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:
nums = new int[][]; // ILLEGAL - NEEDS 1ST DIMENSION
nums = new int[5][]; // OK
nums = new int[5][4]; // OK
Elements of the Array: if nums is a 2D array as shown above,
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.
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];
This creates an array of 10x20x30=6000 integers.
temperature is an array of array of arrays
SubArrays:
temperature is a 3D array of size 10x20x30. There is one of these.
temperature[i] is a 2D array of size 20x30. There are 10 of these.
temperature[i][j] is a 1D array of size 30. There are 200 of these.
All but the last dimension must be initially specified:
int temperature[][][] = new int[10][10][]; // OK
int temperature[][][] = new int[10][][]; // NOT OK