Java Reference
In-Depth Information
But if we turn this loop around and have it iterate backwards rather than going for-
wards, it does work properly:
// works properly because loop goes backwards
for (int i = words.size() - 1; i >= 0; i ) {
words.add(i, "~");
}
The problem with the original code was that we were inserting a value into the list
and then moving our index variable onto that spot in the list. If instead we work
backwards, the changes that we make affect only those parts of the list that we have
already processed.
Similarly, we tried to write the second loop as follows:
// doesn't work properly
for (int i = 0; i < words.size(); i += 2) {
words.remove(i);
}
Again, the problem was that we were changing a part of the list that we were about
to process. We can keep the overall structure intact by running the loop backwards:
// works properly because loop goes backwards
for (int i = words.size() - 2; i >= 0; i -= 2) {
words.remove(i);
}
Using the For-Each Loop with ArrayLists
You saw in Chapter 7 that you can use a for-each loop to iterate over the elements of
an array. You can do the same with an ArrayList . For example, earlier we men-
tioned that the following code could be used to add up the lengths of the String s
stored in an ArrayList<String> called list :
int sum = 0;
for (int i = 0; i < list.size(); i++) {
String s = list.get(i);
sum += s.length();
}
System.out.println("Total of lengths = " + sum);
We can simplify this code with a for-each loop. Remember that the syntax of this
kind of loop is as follows:
 
Search WWH ::




Custom Search