Java Reference
In-Depth Information
An
ArrayList
object is an
Iterable
object. Therefore,
for example, if
library
is an
ArrayList<Book>
object (that
is, an
ArrayList
that manages
Book
objects), we can use
a
for
loop to process each
Book
object in the collection as
follows:
KEY CONCEPT
The for-each version of a
for
loop
simplifies the processing of all ele-
ments in an
Iterable
object.
for
(Book myBook : library)
System.out.println (myBook);
This code can be read as follows: for each
Book
in
library
, print the topic
object
.
The variable
myBook
takes the value of each
Book
object in the collection in
turn, and the body of the loop can process it appropriately. That succinct for-each
loop is essentially equivalent to the following:
Book myBook;
while
(bookList.hasNext())
{
myBook = bookList.next();
System.out.println (myBook);
}
This version of the
for
loop can also be used on arrays, which are discussed in
Chapter 8. We use the for-each loop as appropriate in various situations through-
out the rest of the topic.
Comparing Loops
The three basic loop statements (
while
,
do
, and
for
) are functionally equivalent.
Any particular loop written using one type of loop can be written using either of
the other two loop types. Which type of loop we use depends on the situation.
As we mentioned earlier, the primary difference between a
while
loop and a
do
loop is when the condition is evaluated. If we know we want to execute the loop
body at least once, a
do
loop is usually the better choice. The body of a
while
loop, on the other hand, might not be executed at all if the condition is initially
false. Therefore, we say that the body of a
while
loop is executed zero or more
times, but the body of a
do
loop is executed one or more times.
A
for
loop is like a
while
loop in that the condition is
evaluated before the loop body is executed. We generally
use a
for
loop when the number of times we want to iterate
through a loop is fixed or can be easily calculated. In many
situations, it is simply more convenient to separate the code
that sets up and controls the loop iterations inside the
for
loop header from the
body of the loop.
KEY CONCEPT
The loop statements are function-
ally equivalent. Which one you use
should depend on the situation.
Search WWH ::
Custom Search