Java Reference
In-Depth Information
the language, then older programs that happened to use those identifiers as variable or
method names (such as System.in ) would no longer have compiled correctly.
You don't have to use the Ȓfor eachȓ construct to loop through all elements in an
array. You can implement the same loop with a straightforward for loop and an
explicit index variable:
double[] data = . . .;
double sum = 0;
for (int i = 0; i < data.length; i++)
{
double e = data[i];
sum = sum + e;
}
Note an important difference between the Ȓfor eachȓ loop and the ordinary for loop.
In the Ȓfor eachȓ loop, the element variable e is assigned values data[0],
data[1] , and so on. In the ordinary for loop, the index variable i is assigned
values 0, 1, and so on.
You can also use the enhanced for loop to visit all elements of an array list. For
example, the following loop computes the total value of all accounts:
ArrayList<BankAccount> accounts = . . . ;
double sum = 0;
for (BankAccount a : accounts)
{
sum = sum + a.getBalance();
}
300
301
This loop is 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();
}
The Ȓfor eachȓ loop has a very specific purpose: traversing the elements of a
collection, from the beginning to the end. Sometimes you don't want to start at the
beginning, or you may need to traverse the collection backwards. In those situations,
do not hesitate to use an ordinary for loop.
Search WWH ::




Custom Search