Java Reference
In-Depth Information
You can also achieve the same result with slightly less code using the fill() method from the Arrays
class that you saw earlier:
for(int i = 0; i < samples.length; ++i) {
java.util.Arrays.fill(samples[i], 99.0f); // Initialize elements in a row to 99
}
Because the fill() method fills all the elements in a row, you need only one loop that iterates over the
rows of the array.
Multidimensional Arrays
You are not limited to two-dimensional arrays either. If you are an international java bean grower with mul-
tiple farms across several countries, you could arrange to store the results of your bean counting in the array
declared and defined in the following statement:
long[][][] beans = new long[5][10][30];
The array, beans , has three dimensions. It provides for holding bean counts for each of up to 30 fields
per farm, with 10 farms per country in each of 5 countries.
You can envisage this as just a three-dimensional array, but remember that beans is really an array of five
elements, each of which holds a reference to a two-dimensional array, and each of these two-dimensional
arrays can be different. For example, if you really want to go to town, you can declare the array beans with
the statement:
long[][][] beans = new long[3][][]; // Three two-dimensional arrays
Each of the three elements in the first dimension of beans can hold a different two-dimensional array, so
you could specify the first dimension of each explicitly with the following statements:
beans[0] = new long[4][];
beans[1] = new long[2][];
beans[2] = new long[5][];
These three arrays have elements that each hold a one-dimensional array, and you can also specify the
sizes of these independently. Note how the empty square brackets indicate there is still a dimension un-
defined. You could give the arrays in each of these elements random dimensions between 1 and 7 with the
following code:
for(int i = 0; i < beans.length; ++i) // Vary over 1st dimension
for(int j = 0; j < beans[i].length; ++j) // Vary over 2nd dimension
beans[i][j] = new long[(int)(1.0 + 6.0*Math.random())];
If you can find a sensible reason for doing so, or if you are just a glutton for punishment, you can extend
this to four or more dimensions.
Arrays of Characters
Search WWH ::




Custom Search