Java Reference
In-Depth Information
inStock
[RED]
[BROWN]
[BLACK]
[WHITE]
[GRAY]
[GM]
10
7
12
10
4
[FORD]
18
11
15
17
10
[TOYOTA]
12
10
9
5
12
[BMW]
16
6
13
8
3
[NISSAN]
10
7
12
6
4
[VOLVO]
9
4
7
12
11
FIGURE 9-15 Table inStock
You can see that the data is in a table format. The table has 30 entries, and every entry is an
integer.Becausea lthetableentriesareofthesametype,youcoulddeclareaone-
dimensional array of 30 elements of type int . The first five elements of the one-dimensional
array could store the data of the first row of the table, the next five elements of the one-
dimensional array could store the data of the second row of the table, and so on. In other
words, you could simulate the data given in a table format in a one-dimensional array.
If you do so, the algorithms to manipulate the data in the one-dimensional array will be
somewhat complicated, because you must carefully note where one row ends and another
begins. Also, you would need to correctly compute the index of a particular element from
its row and column location. Java simplifies manipulating data in a table format by using
two-dimensional arrays. This section first discusses how to declare two-dimensional
arrays, and then looks at ways to manipulate the data in a two-dimensional array.
Two-dimensional array: A collection of a fixed number of elements arranged in rows and
columns (that is, in two dimensions), wherein all the elements are of the same type.
A syntax for declaring a two-dimensional array is:
dataType[][] arrayName;
where dataType is the data type of the array elements.
Because an array is an object, we must instantiate the object to allocate memory space to
store the data. The general syntax to instantiate a two-dimensional array object is:
arrayName = new dataType[intExp1][intExp2];
where intExp1 and intExp2 are expressions yielding positive integer values. The two
expressions, intExp1 and intExp2 , specify the number of rows and the number of
columns, respectively, in the array.
Search WWH ::




Custom Search