Java Reference
In-Depth Information
Adding to and Removing from an ArrayList
In this section we will explore some of the issues that come up when you dynami-
cally add values to or remove values from the middle of an ArrayList . The results
are often surprising, so it is worth exploring the common pitfalls.
Consider the following code, which creates an ArrayList and stores several
words in it:
ArrayList<String> words = new ArrayList<String>();
words.add("four");
words.add("score");
words.add("and");
words.add("seven");
words.add("years");
words.add("ago");
System.out.println("words = " + words);
This code produces the following output:
words = [four, score, and, seven, years, ago]
We'll explore the problem of inserting a tilde (“~”) in front of each word, doubling
the size of the list. Inserting tildes isn't the most exciting operation you can imagine
doing with a list, but we want to keep things simple so we can focus on the program-
ming issues, and you'll find that you often want to perform operations like this. For
example, if you put a tilde in front of a search term, Google does a different search
that includes synonyms of the word. Searching for “~four ~score” yields more than
10 times as many pages as searching for just “four score.”
In our case we want to keep the tildes separate from the words themselves, so we
want to insert a new String containing just a tilde in front of each word in the list.
Here is a first attempt that makes sense intuitively but doesn't work:
// doesn't work properly
for (int i = 0; i < words.size(); i++) {
words.add(i, "~");
}
System.out.println("after loop words = " + words);
This for loop is a slight variation of the standard array-traversal loop. It has an
index variable i whose value starts at 0 and goes up by one each time. In this case,
the loop is inserting a tilde at position i each time it executes the loop. The problem
is that the loop never terminates. (If you're patient enough, you will find that the pro-
gram does eventually terminate with an “out of memory” error.)
 
 
Search WWH ::




Custom Search