Java Reference
In-Depth Information
Putting all of these pieces together gives us the following complete program:
1 // Builds up a list of words, adds tildes, and removes them.
2
3 import java.util.*;
4
5 public class TildeFun {
6 public static void main(String[] args) {
7 // construct and fill up ArrayList
8 ArrayList<String> words = new ArrayList<String>();
9 words.add("four");
10 words.add("score");
11 words.add("and");
12 words.add("seven");
13 words.add("years");
14 words.add("ago");
15 System.out.println("words = " + words);
16
17 // insert one tilde in front of each word
18 for ( int i = 0; i < words.size(); i += 2) {
19 words.add(i, "~");
20 }
21 System.out.println("after loop words = " + words);
22
23 // remove tildes
24 for ( int i = 0; i < words.size(); i++) {
25 words.remove(i);
26 }
27 System.out.println("after second loop words = " + words);
28 }
29 }
If we want to write the loops in a more intuitive manner, we can run them back-
wards. The loops we have written go from left to right, from the beginning of the list
to the end of the list. We could instead go from right to left, from the end of the list to
the beginning of the list. By going backwards, we ensure that any changes we are
making occur in parts of the list that we have already visited.
For example, we found that the following loop did not work properly even though
it seemed like the intuitive approach:
// doesn't work properly
for (int i = 0; i < words.size(); i++) {
words.add(i, "~");
}
Search WWH ::




Custom Search