Java Reference
In-Depth Information
As in the
if
and
while
statements, the braces are optional when only a
single statement is involved, but good practice compels us always to use the
braces. Additional code can easily be added without messing up the logic—
should one forget, at that point, the need to add braces.
Speaking of the
while
loop: When do you use a
for
and when do you
use a
while
loop? The big advantage of the
for
loop is its readability. It con-
solidates the loop control logic into a single place—within the parentheses.
Anyone reading your code can see at once what variable(s) are being used to
control how many times the loop executes and what needs to be done on each
iteration (e.g., just increment
i
). If no initialization is needed before starting
the loop, or if the increment happens indirectly as part of what goes on in the
body of the loop, then you might as well use a
while
loop. But when the ini-
tialization and iteration parts can be clearly spelled out, use the
for
loop for
the sake of the next programmer who might be reading your code.
The
for
loop with iterators.
As of Java 5.0, there is additional syntax for a
for
loop. It is meant to provide a useful shorthand when looping over the
members of an iterator.
4
So what's an iterator? Well, it has to do with collec-
tions. Uh, oh, we're surrounded by undefined terms. One step at a time, here.
Java has a whole bunch (we won't say “collection,” it's a loaded term) of utility
classes that come with it. We mentioned these classes in our discussion of
Javadoc. While not part of the language syntax, some of these classes are so
useful that you will see them throughout many, if not most, Java programs.
Collection is a generic term (in fact, it's a Java interface) for several classes
that allow you to group similar objects together. It covers such classes as
Lists
,
LinkedLists
,
Hashtables
,
Sets
, and the like. They are implementations of
all those things that you (should have) learned in a Data Structures course in
school. Typically you want to add (and sometimes remove) members from a
collection, and you may also want to look something up in the collection. (If
you're new to collections, think “array,” as they are a simple and familiar type
of collection.) Sometimes, though, you don't want just one item from the col-
lection, but you want to look at all of the objects in the collection, one at a
time. The generic way to do that, the way that hides the specifics of what kind
of collection you have (linked list, or array, or map) is called an iterator.
5
4. This feature is related to the topic of templates and generics. See Section 3.5.
5. The earliest versions of Java used an object called an
Enumeration
. It does much the same
thing as an iterator, but with somewhat clumsier method names. Iterators also allow for a