Java Reference
In-Depth Information
S YNTAX 7.3: The Ñfor eachÒ Loop
for (Type variable : collection) statement
Example:
for (double e : data)
sum = sum + e;
Purpose:
To execute a loop for each element in the collection. In each iteration, the variable
is assigned the next element of the collection. Then the statement is executed.
S ELF C HECK
7. Write a Ȓfor eachȓ loop that prints all elements in the array data .
8. Why is the Ȓfor eachȓ loop not an appropriate shortcut for the following
ordinary for loop?
for (int i = 0; i < data.length; i++) data[i] =
i * i;
7.5 Simple Array Algorithms
7.5.1 Counting Matches
To count values in an array list, check all elements and count the matches until
you reach the end of the array list.
Suppose you want to find how many accounts of a certain type you have. Then you
must go through the entire collection and increment a counter each time you find a
match. Here we count the number of accounts whose balance is at least as much as
a given threshold:
public class Bank
{
public int count(double atLeast)
301
302
Search WWH ::




Custom Search