Java Reference
In-Depth Information
7.1 Introduction
Data in a table or a matrix can be represented using a two-dimensional array.
Key
Point
The preceding chapter introduced how to use one-dimensional arrays to store linear collec-
tions of elements. You can use a two-dimensional array to store a matrix or a table. For exam-
ple, the following table that lists the distances between cities can be stored using a
two-dimensional array named distances .
problem
Distance Table (in miles)
Chicago
Boston
New York
Atlanta
Miami
Dallas
Houston
0
983
787
714
1375
967
1087
Chicago
Boston
983
0
214
1102
1763
1723
1842
New York
787
214
0
888
1549
1548
1627
Atlanta
714
1102
888
0
661
781
810
Miami
1375
1763
1549
661
0
1426
1187
Dallas
967
1723
1548
781
1426
0
239
Houston
1087
1842
1627
810
1187
239
0
double [][] distances = {
{ 0 , 983 , 787 , 714 , 1375 , 967 , 1087 },
{ 983 , 0 , 214 , 1102 , 1763 , 1723 , 1842 },
{ 787 , 214 , 0 , 888 , 1549 , 1548 , 1627 },
{ 714 , 1102 , 888 , 0 , 661 , 781 , 810 },
{ 1375 , 1763 , 1549 , 661 , 0 , 1426 , 1187 },
{ 967 , 1723 , 1548 , 781 , 1426 , 0 , 239 },
{ 1087 , 1842 , 1627 , 810 , 1187 , 239 , 0 },
};
7.2 Two-Dimensional Array Basics
An element in a two-dimensional array is accessed through a row and column index.
Key
Point
How do you declare a variable for two-dimensional arrays? How do you create a two-
dimensional array? How do you access elements in a two-dimensional array? This section
addresses these issues.
7.2.1 Declaring Variables of Two-Dimensional Arrays and Creating
Two-Dimensional Arrays
The syntax for declaring a two-dimensional array is:
elementType[][] arrayRefVar;
or
elementType arrayRefVar[][]; // Allowed, but not preferred
As an example, here is how you would declare a two-dimensional array variable matrix
of int values:
int [][] matrix;
 
 
 
 
Search WWH ::




Custom Search