An array is a container for similar items. For example, we can have an array of integers, or an array of booleans or an array of House objects (if House is a defined class).
The elements in the array can be any valid data type. Since an array is a valid data type, we can also
have an array of arrays. These give rise to multidimensional arrays. For example, a 2-dimensional
array, called array2d can be created as follows:
int array2d[][] = new int[10][20];Here,
array2d is an array of size 10 (it can store 10 elements in it). Each array element
of array2d is itself
an integer array of size 20;
Perhaps more intuitively, we can view array2d as a table of integers with 10 rows and 20 columns.
Equivalently, we
can view it as a 2-dimensional 10x20 matrix. To access/modify individual data elements (integers in this case), we
need to specify two index values; one for the row and one for the column.
// get integer in array with row index 1 and column index 3 // (2nd row and 4th column) System.out.println( array2d[1][3] ); // set array element with row index 0 and column index 0 (to be 10) array2d[0][0] = 10; // ERROR! Each index gets its own square brackets array2d[1,3] = 3; //!ERROR!//Two dimensional arrays are very useful when we deal with data that naturally can be modelled in two dimensions. For example, pixels on a screen or a chess board are naturally modelled with a 2-dimensional array.
We can also have multidimensional arrays with more than two dimensions. For example, a 3-dimensional array can be created as follows:
double temp[][][] = new double[24][18][20];This array might be used to model the temperature in an oven with length 24cm, width 18cm, and height 20cm. Each element might represent the temperature in a given cubic cm in the oven.
Accessing elements in the array is done just as
with a 1- or 2-dimensinal array, but we need to
give three index values, each in their own
square brackets. So, temp[1][4][0] would
access a single double in the position specified.
The variable temp from above is a
3-dimensional array. So what is a 3-dimensional array?
(It is an array of arrays of arrays!)
In this case, it is an array of size 24, whose elements
are each arrays of size 18, whose elements
are each arrays of 20 doubles.
With multidimensional arrays, we don't always have to access one single element. For example,
temp[1][2][17]; // this is a single data element (double)
temp[3][5]; // this is an array of 20 doubles
temp[9]; // this is a 2-dimensional array
// (it has 18 elements, each of which
// are an array of 20 doubles)
temp; // this is a 3-dimensional array
We can use any of these in our code depending on the situation.