Java Reference
In-Depth Information
The indexed variables for this array each have two indices. For example, page[0][0] ,
page[15][32] , and page[29][99] are three of the indexed variables for this array. Note
that each index must be enclosed in its own set of square brackets. As was true of the
one-dimensional arrays we have already seen, each indexed variable for a multidimen-
sional array is a variable of the base type, in this case the type char .
An array may have any number of indices, but perhaps the most common number of
indices is two. A two-dimensional array can be visualized as a two-dimensional display
with the first index giving the row and the second index giving the column. For example,
the array indexed variables of the two-dimensional array a , declared and created as
indexed
variables
char [][] a = new char [5][12];
can be visualized as follows:
a[0][0], a[0][1], a[0][2], ..., a[0][11]
a[1][0], a[1][1], a[1][2], ..., a[1][11]
a[2][0], a[2][1], a[2][2], ..., a[2][11]
a[3][0], a[3][1], a[3][2], ..., a[3][11]
a[4][0], a[4][1], a[4][2], ..., a[4][11]
You might use the array a to store all the characters on a (very small) page of text that has
five lines (numbered 0 through 4) and 12 characters on each line (numbered 0 through 11).
Declaring and Creating a Multidimensional Array
You declare a multidimensional array variable and create a multidimensional array object in
basically the same way that you create and name a one-dimensional array. You simply use as
many square brackets as there are indices.
SYNTAX
Base_Type [] ... [] Variable_Name = new Base_Type [ Length_l ] ... [ Length_n ];
EXAMPLES
char [][] a = new char [5][12];
char [][] page = new char [30][100];
double [][] table = new double [100][10];
int [][][] figure = new int [10][20][30];
Person[][] entry = new Person[10][10];
Person is a class.
In Java, a two-dimensional array, such as a , is actually an array of arrays. The above
array a is actually a one-dimensional array of size 5 , whose base type is a one-dimensional
array of characters of size 12 . This is diagrammed in Display 6.17. As shown in that
display, the array variable a contains a reference to a one-dimensional array of length 5
with a base type of char[] ; that is, the base type of a is the type for an entire one-
dimensional array of characters. Each indexed variable a[0] , a[1] , and so forth con-
tains a reference to a one-dimensional array of characters.
A multi-
dimensional
array is an
array of
arrays
Search WWH ::




Custom Search