Java Reference
In-Depth Information
No matter which Java version you use, you should know that storing wrapped
numbers is quite inefficient. The use of wrappers is acceptable for short array lists,
but you should use arrays for long sequences of numbers or characters.
S ELF C HECK
5. What is the difference between the Types double and Double ?
6. Suppose data is an ArrayList<Double> of size>0. How do you
increment the element with index 0?
299
300
7.4 The Enhanced for Loop
Java version 5.0 introduces a very convenient shortcut for a common loop type.
Often, you need to iterate through a sequence of elementsȌsuch as the elements of
an array or array list. The enhanced for loop makes this process particularly easy to
program.
The enhanced for loop traverses all elements of a collection.
Suppose you want to total up all data values in an array data. Here is how you use the
enhanced for loop to carry out that task.
double[] data = . . .;
double sum = 0;
for (double e : data)
{
sum = sum + e;
}
The loop body is executed for each element in the array data . At the beginning of
each loop iteration, the next element is assigned to the variable e . Then the loop body
is executed. You should read this loop as Ȓfor each e in dataȓ.
You may wonder why Java doesn't let you write Ȓ for each (e in data) ȓ.
Unquestionably, this would have been neater, and the Java language designers
seriously considered this. However, the Ȓfor eachȓ construct was added to Java
several years after its initial release. Had new keywords each and in been added to
Search WWH ::




Custom Search