Java Reference
In-Depth Information
Notice how you use the length of the array, samples.length , all over the place. It appears in the for
loop and in floating-point form as a divisor to calculate the average. When you use arrays, you often find
that references to the length of the array are strewn all through your code. As long as you use the length
member of the array, the code is independent of the number of array elements. If you change the number
of elements in the array, the code automatically deals with that. You should always use the length member
when you need to refer to the length of an array — never use explicit values.
Using the Collection-Based for Loop with an Array
You can use a collection-based for loop as an alternative to the numerical for loop when you want to pro-
cess the values of all the elements in an array. For example, you could rewrite the code fragment from the
previous section that calculated the average of the values in the samples array like this:
double average = 0.0; // Variable to hold the average
for(double value : samples) {
average += value; // Sum all the elements
}
average /= samples.length; // Divide by the total number of elements
The for loop iterates through the values of all elements of type double in the samples array in sequence.
The value variable is assigned the value of each element of the samples array in turn. Thus, the loop
achieves the same result as the numerical for loop that you used earlier — the sum of all the elements is ac-
cumulated in average . When you are processing all the elements in an array, you should use the collection-
based for loop because it is easier to read and less error-prone than the numerical for loop. Of course, when
you want to process only data from part of the array, you still must use the numerical for loop with the loop
counter ranging over the indexes for the elements you want to access.
It's important to remember that the collection-based for loop iterates over the values stored in an array.
It does not provide access to the elements for the purpose of setting their values. Therefore, you use it only
when you are accessing all the values stored in an array to use them in some way. If you want to recalculate
the values in the array, use the numerical for loop.
Let's try out an array in an improved program to calculate prime numbers:
TRY IT OUT: Even More Primes
Try out the following code, derived, in part, from the code you used in Chapter 3:
import static java.lang.Math.ceil;
import static java.lang.Math.sqrt;
public class MorePrimes {
public static void main(String[] args) {
long[] primes = new long[20];
// Array to store primes
primes[0] = 2L;
// Seed the first prime
Search WWH ::




Custom Search