Programming and Problem Solving with Java

(やまだぃちぅ) #1

(^582) | Multidimensional Arrays and Numeric Computation


12.1 Two-Dimensional Arrays


A one-dimensional array is used to represent items in a list or a sequence of values. A two-
dimensional arrayis used to represent items in a table with rows and columns, provided each
item in the table is of the same type or class. We access a component in a two-di-
mensional array by specifying the row and column indexes of the item in the ar-
ray. This task is a familiar one. For example, if you want to find a street on a map,
you look up the street name on the back of the map to find the coordinates of the
street, usually a number and a letter. The number specifies a row, and the letter
specifies a column. You find the street where the row and column intersect.
Figure 12.1 shows a two-dimensional array with 100 rows and 9 columns. The
rows are accessed by an integer ranging from 0 through 99; the columns are ac-
cessed by an integer ranging from 0 through 8. Each component is accessed by a
row–column pair—for example, (0, 5).

Array Declaration and Instantiation


We declare a two-dimensional array variable in exactly the same way that we declare a one-
dimensional array variable, except that we use two pairs of brackets. Likewise, we instanti-
ate a two-dimensional array object in exactly the same way, except that we must specify sizes
for two dimensions. Below is the syntax template for declaring an array with two dimensions:

Two-dimensional array A col-
lection of components, all of the
same type, structured in two di-
mensions. Each component is
accessed by a pair of indexes
that represent the component’s
position in each dimension.

alpha

[ 0 ]
[ 0 ]

[ 1 ]

[ 2 ]

[ 3 ]

[ 98 ]

[ 99 ]

[ 1 ][ 2 ][ 3 ][ 4 ][ 5 ][ 6 ][ 7 ][ 8 ]
Row 0, column 5

Row 98, column 2

Figure 12.1 alphaArray
Free download pdf