Java Reference
In-Depth Information
starting with the first value—in other words, the values that are currently at indexes
0, 2, 4, 6, 8, and 10. We might write code like the following:
// doesn't work properly
for (int i = 0; i < words.size(); i += 2) {
words.remove(i);
}
System.out.println("after second loop words = " + words);
Looking at the loop, you can see that i starts at 0 and goes up by 2 each time,
which means it produces a sequence of even values ( 0 , 2 , 4 , and so on). That seems
to be what we want, given that the values to be removed are at those indexes. But this
code doesn't work. It produces the following output:
after second loop words = [four, ~, ~, and, seven, ~, ~, ago]
Again, the problem comes from the fact that in the ArrayList values are shifted
dynamically from one location to another. The first tilde we want to remove is at
index 0:
[~, four, ~, score, ~, and, ~, seven, ~, years, ~, ago]
But once we remove the tilde at position 0, everything is shifted one position to
the left. The second tilde moves into index 1:
[four, ~, score, ~, and, ~, seven, ~, years, ~, ago]
So the second remove should be at index 1, not index 2. And once we perform that
second remove, the third tilde will be in index 2:
[four, score, ~, and, ~, seven, ~, years, ~, ago]
In this case, we don't want to increment i by 2 each time through the loop. Here,
the simple loop that increments by 1 is the right choice:
for (int i = 0; i < words.size(); i++) {
words.remove(i);
}
System.out.println("after second loop words = " + words);
After the program executes this code, it produces the following output:
after second loop words = [four, score, and, seven, years, ago]
 
Search WWH ::




Custom Search