See handout for intro to ArrayLists, Beatles.java. Competition to bands example in our text.
Programming Problem solved by ArrayList
Consider
program to reverse the order of words given in a file: this requires storing
the input in memory and then outputting it in reverse order.
input file hamlet.txt, as on pg. 380.
To be or
not to be
java ReverseWords
be to not or be To
We need to read in the words
from an input file and hold them in memory until we output them.
If we use an array to hold
the words, we need to decide how big it will be. But we really don't know how
big to make it. That's where ArrayList comes in: it stretches and stretches to
hold any number of objects.
ArrayList<String> words = new
ArrayList<String>(); // start with
empty ArrayList
// in the input loop, like on pg.
380:
String word = input.next();
words.add(word); // add word on at end
// Later after the input loop,
output them in reverse order:
for (int i = words.size()-1;
i>=0; i--) {
System.out.println(words.get(i) + “ “);
}
Continue next Thursday.