Java Reference
In-Depth Information
7.5 Multidimensional Arrays
The array examples in the previous sections all involved what are known as one-
dimensional arrays (a single row or a single column of data). Often, you'll want to
store data in a multidimensional way. For example, you might want to store a two-
dimensional grid of data that has both rows and columns. Fortunately, you can form
arrays of arbitrarily many dimensions:
double: one double
double[]: a one-dimensional array of double s
double[][]: a two-dimensional grid of double s
double[][][]: a three-dimensional collection of double s
. . .
Arrays of more than one dimension are called multidimensional arrays.
Multidimensional Array
An array of arrays, the elements of which are accessed with multiple inte-
ger indexes.
Rectangular Two-Dimensional Arrays
The most common use of a multidimensional array is a two-dimensional array of a
certain width and height. For example, suppose that on three separate days you took a
series of five temperature readings. You can define a two-dimensional array that has
three rows and five columns as follows:
double[][] temps = new double[3][5];
Notice that on both the left and right sides of this assignment statement, you have
to use a double set of square brackets. When you are describing the type on the left,
you have to make it clear that this is not just a one-dimensional sequence of values,
which would be of type double[] , but instead a two-dimensional grid of values,
which is of type double[][] . On the right, when you construct the array, you must
specify the dimensions of the grid. The normal convention is to list the row first fol-
lowed by the column. The resulting array would look like this:
[0]
[1]
[2]
[3]
[4]
[0]
0.0
0.0
0.0
0.0
0.0
temps
[1]
0.0
0.0
0.0
0.0
0.0
[2]
0.0
0.0
0.0
0.0
0.0
As with one-dimensional arrays, the values are initialized to 0.0 and the indexes
start with 0 for both rows and columns. Once you've created such an array, you can
refer to individual elements by providing specific row and column numbers (in that
 
 
Search WWH ::




Custom Search