The Generalized for Loop
Traverses all elements of a collection:
double[] data = . . .;
double sum = 0;
for (double e : data) // You should read this loop as "for each e in data"
{
sum = sum + e;
}
Traditional alternative:
double[] data = . . .;
double sum = 0;
for (int i = 0; i < data.length; i++)
{
double e = data[i];
sum = sum + e;
}
Works for ArrayLists too:
ArrayList<BankAccount> accounts = . . . ;
double sum = 0;
for (BankAccount a : accounts)
{
sum = sum + a.getBalance();
}
Equivalent to the following ordinary for loop:
double sum = 0;
for (int i = 0; i < accounts.size(); i++)
{
BankAccount a = accounts.get(i);
sum = sum + a.getBalance();
}
Write a "for each" loop that prints all elements in the array data.
Answer:
for (double x : data) System.out.println(x);
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;
Answer: The loop writes a value into data[i]. The "for each" loop does not have the index variable i.