Java Reference
In-Depth Information
for (<type> <name> : <structure>) {
<statement>;
<statement>;
...
<statement>;
}
Thus, the preceding loop to add up the lengths of the
String
s can be rewritten as
follows:
int sum = 0;
for (String s : list) {
sum += s.length();
}
System.out.println("Total of lengths = " + sum);
This loop is another way of saying, “For each
String s
contained in
list
....”
Because the for-each loop has such a simple syntax, you should use it whenever
you want to process each value stored in a list sequentially. You will find, however,
that the for-each loop is not appropriate for more complex list problems. For exam-
ple, there is no simple way to skip around in a list using a for-each loop. You must
process the values in sequence from first to last. Also, you cannot modify the list
while you are iterating over it.
Consider, for example, the following sample code:
// this doesn't work
for (String s : words) {
System.out.println(s);
words.remove(0);
}
This code prints each
String
from the list and then attempts to remove the value
at the front of the list. When you execute this code, the program halts with a
ConcurrentModificationException
. Java is letting you know that you are not
allowed to iterate over the list and to modify the list at the same time (concurrently).
Because of this limitation, neither of the problems discussed in the previous section
could be solved using a for-each loop.
So far, all of the
ArrayList
examples we have studied have involved
ArrayList
s of
String
objects. What if you wanted to form a list of integers? Given that
ArrayList<E>
is a generic class, you'd think that Java would allow you to define an
ArrayList<int>
, but that is not the case. The
E
in
ArrayList<E>
can be filled in with
any object or reference type (i.e., the name of a class). The primitive types (e.g.,
int
,
double
,
char
, and
boolean
), cannot be used as type parameters for an
ArrayList
.
Instead, Java defines a series of
wrapper classes
that allow you to store primitive
data as objects.
Search WWH ::
Custom Search