Java Reference
In-Depth Information
Discussion
As mentioned back in
Using Arrays for Data Structuring
,
Java arrays can hold any reference
type. Because an array is a reference type, it follows that you can have arrays of arrays or, in
other terminology,
multidimensional
arrays. Further, because each array has its own length
attribute, the columns of a two-dimensional array, for example, do not all have to be the same
length (see
Figure 7-3
).
Here is code to allocate a couple of two-dimensional arrays, one using a loop and the other
using an initializer. Both are selectively printed:
public
public class
class
ArrayTwoDObjects
ArrayTwoDObjects
{
/** Return list of subscript names (unrealistic; just for demo). */
public
public static
static
String
[][]
getArrayInfo
() {
String info
[][];
info
=
new
new
String
[
10
][
10
];
for
for
(
int
int
i
=
0
;
i
<
info
.
length
;
i
++) {
for
for
(
int
int
j
=
0
;
j
<
info
[
i
].
length
;
j
++) {
info
[
i
][
j
] =
"String["
+
i
+
","
+
j
+
"]"
;
}
}
return
return
info
;
}
/** Return list of allowable parameters (Applet method). */
public
public static
static
String
[][]
getParameterInfo
() {
String param_info
[][] = {
{
"fontsize"
,
"9-18"
,
"Size of font"
},
{
"URL"
,
"-"
,
"Where to download"
},
};
return
return
param_info
;
}
/** Run both initialization methods and print part of the results */
public
public static
void
main
(
String
[]
args
) {
print
(
"from getArrayInfo"
,
getArrayInfo
());
print
(
"from getParameterInfo"
,
getParameterInfo
());
static
void
}
/** Print selected elements from the 2D array */
public
public static
void
print
(
String tag
,
String
[][]
array
) {
System
.
out
.
println
(
"Array "
+
tag
+
" is "
+
array
.
length
+
" x "
+
array
[
0
].
length
);
static
void