Java Reference
In-Depth Information
Youcansubsequentlyoutputthesevaluesinatabularformatbyusingaforloop,as
demonstrated by the following example—the code makes no attempt to align the tem-
perature values in perfect columns:
for (int row = 0; row < temperatures.length; row++)
{
for (int col = 0; col < temperatures[row].length; col++)
System.out.print(temperatures[row][col]+" ");
System.out.println();
}
Javaprovidesanalternativeforcreatingamultidimensionalarrayinwhichyoucreate
eachdimension separately.Forexample, tocreate atwo-dimensional arrayvia
new
in
thismanner,firstcreateaone-dimensionalrowarray(theouterarray),andthencreatea
one-dimensional column array (the inner array), as demonstrated here:
// Create the row array.
double[][] temperatures = new double[3][]; // Note the ex-
tra empty pair of brackets.
// Create a column array for each row.
for (int row = 0; row < temperatures.length; row++)
temperatures[row] = new double[2]; // 2 columns per row
Thiskindofanarrayisknownasa
ragged array
becauseeachrowcanhaveadiffer-
ent number of columns; the array is not rectangular, but is ragged.
Note
Whencreatingtherowarray,youmustspecifyanextrapairofemptybrackets
aspartoftheexpressionfollowing
new
.(Forathree-dimensionalarray—aone-dimen-
sionalarrayoftables,wherethisarray'selementsreferencerowarrays—youmustspe-
cify two pairs of empty brackets as part of the expression following
new
.)
example,
Image[] imArray = new Image[] { new
Image("image0.png"), new Image("image1.png") };
createsapairof
Image
objectsandatwo-element
Image
arrayobjectinitializedtothe
Image
objects'
references, and assigns the array's reference to
imArray
.
When you create an array in this manner, you are not permitted to specify an
integral expression between the square brackets. For example, the compiler reports an
error when it encounters
Image[] imArray = new Image[2] { new
Image("image0.png"), new Image("image1.png") };
. To correct this
error, remove the
2
from between the square brackets.