Multi-Dimensional Arrays
Multidimensional Arrays
Java doesn’t limit arrays to just two dimensions. For example, suppose we decide to extend our rainfall survey to cover a ten-year period. For each year we now need a two-dimensional array. This results in a three dimensional array consisting of an array of years, each of which contains an array of months, each of which contains an array of days:
final int NYEARS = 10; final int NMONTHS = 13; final int NDAYS = 32; double rainfall [][][] = new double [NYEARS][NMONTHS][NDAYS];
Following the design convention of not using the 0 month and 0 days, we end up with a 10 ⇥ 13 ⇥ 32 array. Note the use of final variables to represent the size of each dimension of the array. This helps to make the program more readable.
In Figure 9.23, each year of the rainfall data is represented as a separate page. On each page, there is a two-dimensional table that consists of 12 rows (1 per month) and 31 columns (1 per day).
Figure 9.23: Three-dimensional data might be viewed as a collection of pages, each of which contains a two-dimensional table
As you might expect, algorithms for processing each element in a threedimensional table would require a three-level nested loop. For example, the following algorithm would be used to initialize all elements of our three-dimensional rainfall array:
Note again the proper use of the length attribute for each of the three dimensions of the array. In the outer loop, rainfall.length, we’re referring to the number of years. In the middle loop, rainfall[year].length, we’re referring to number of months
within a given year. In the inner loop, rainfall[year][month].length, we’re referring to the number of days within a month.
If we added a fourth dimension to our array and wanted to extend this algorithm to initialize it, we would simply embed the three-level loop within another for loop that would iterate over each city.
Source: R. Morelli and R. Walde, Trinity College
This work
is licensed under a Creative Commons Attribution 4.0 License.