Java Reference
In-Depth Information
The loop fails to terminate because the ArrayList structure is dynamic in nature.
Let's think about this carefully to see what's happening. Initially we have the follow-
ing list, with the String "four" in position 0:
[four, score, and, seven, years, ago]
The first time the program executes the loop, it inserts a tilde at position 0. To
make room for the tilde at position 0, the ArrayList has to shift all the other values
one place to the right. As a result, the String "four" ends up in position 1:
[~, four, score, and, seven, years, ago]
Then we come around the for loop, increment i to be 1 , and insert a tilde at posi-
tion 1. But because the word "four" is currently at position 1, this second tilde also
goes in front of the word "four" , shifting it into position 2:
[~, ~, four, score, and, seven, years, ago]
We then go around the loop again, incrementing i to be 2 and inserting a tilde at
that position, which is once again in front of the word "four" :
[~, ~, ~, four, score, and, seven, years, ago]
This loop continues indefinitely, because we keep inserting tildes in front of the
first word in the list. The for loop test compares i to the size of the list, but because
the list is growing, the size keeps going up. So, this process continues until all the
computer's available memory is exhausted.
To fix this loop, we have to take into account the fact that inserting a tilde at posi-
tion i is going to shift everything one place to the right. So, on the next iteration of
the loop, we will want to insert the tilde in the position that is two to the right, not
one to the right. We can fix the code simply by changing the update part of the for
loop to add 2 to i instead of adding 1 to i :
for (int i = 0; i < words.size(); i += 2) {
words.add(i, "~");
}
System.out.println("after loop words = " + words);
When we execute this version of the code, we get the following output:
after loop words = [~, four, ~, score, ~, and, ~, seven, ~, years, ~, ago]
As another example, let's consider what code we would need to write to undo this
operation. We want to write code that will remove every other value from the list,
Search WWH ::




Custom Search