Java Reference
In-Depth Information
Multidimensional Arrays
The arrays discussed up until now have been one-dimensional (often referred to
as single arrays). In Java, you can create an array of any dimension. For example,
a two-dimensional array (or double array) can be used to store data that is
viewed as rows and columns. A three-dimensional array can be used to store
data that is viewed as rows, columns, and a height dimension. You can create
higher-dimensional arrays as well, although they become hard to visualize.
As with single arrays, multidimensional arrays are objects and require a ref-
erence. The reference is declared using multiple square brackets between the
data type and the variable name. For example, the following statement
declares a reference to a double array of ints:
int [] [] sums;
When instantiating a double array, two ints are used to specify the number
of rows and columns. The following statement assigns sums to a new 10 x 12
array of ints:
sums = new int[10][12];
This array consists of 120 ints because in memory there will be 10 arrays of
12 ints. The sums reference points to an array of size 10, which contains 10 int
array references. Each of the 10 int array references points to an array of 12 ints,
resulting in 120 ints.
A three-dimensional reference looks similar to the following:
String [] [] [] dims;
Instantiating the array involves three values, one for each dimension, as
follows:
dims = new String[5][5][4];
The dims array consists of 5 * 5 * 4 = 100 String objects.
Each element in a two-dimensional array requires two indexes to access it.
In the sums array, the first value is between 0 and 9, and the second value is
between 0 and 11. The following statement assigns the value 5 to the element
in the third column of the fourth row:
sums[3][2] = 5;
Search WWH ::




Custom Search