Java Reference
In-Depth Information
Arrays of Arrays
We have only worked with one-dimensional arrays up to now, that is, arrays that use a single index.
Why would you ever need the complications of using more indexes to access the elements of an array?
Suppose that you have a fanatical interest in the weather, and you are intent on recording the
temperature each day at 10 separate geographical locations throughout the year 2002. Once you have
sorted out the logistics of actually collecting this information, you can use an array of 10 elements
corresponding to the number of locations, where each of these elements is an array of 365 elements to
store the temperature values. You would declare this array with the statement:
float[][] temperature = new float[10][365];
This is called a two-dimensional array , since it has two dimensions - one with index values running
from 0 to 9, and the other with index values from 0 to 364. The first index will relate to a geographical
location, and the second index corresponds to the day of the year. That's much handier than a one-
dimensional array with 3650 elements, isn't it?
The organization of the two-dimensional array is shown in the following diagram.
There are 10 arrays, each having 365 elements. In referring to an element, the first square brackets enclose
the index for a particular array, and the second pair of square brackets enclose the index value for an element
within that array. So to refer to the temperature for day 100 for the sixth location, you would use
temperature[5][99] . Since each float variable occupies 4 bytes, the total space required to store the
elements in this two-dimensional array is 10x365x4 bytes, which is a total of 14,600 bytes.
For a fixed second index value in a two-dimensional array, varying the first index direction is often referred
to as accessing a column of the array. Similarly, fixing the first index value and varying the second, you
access a row of the array. The reason for this terminology is apparent from the last diagram.
You could just as well have used two statements to create the last array, one to declare the array
variable, and the other to define the array:
float [][] temperature; // Declare the array variable
temperature = new float[10][365]; // Create the array
Search WWH ::




Custom Search