Lab 12: More Java Collections

Before proceeding, finish up the previous lab.

This lab continues working with classes from the Java Collections framework (ArrayList, HashMap, HashSet, and Iterator), along with introducing the StringTokenizer class. You'll be a new version of the program that you wrote for the last lab.

1. Review

In the code from the last lab, note how you did the following things:

  1. Used the Iterator generic class explicitly in order to step through the items in an ArrayList or a HashMap's set of keys;
  2. Supplied the compareTo() method for the class SIPair, so that it would implement the Comparable interface; and
  3. Used the generic method Collections.sort() to sort an ArrayList of SIPairs.

Make sure you understand what you had to do for each of these things.

Also make sure that all of your changes are committed to your Mercurial repository.

2. The for-each loop

Copy the FileProcessor.java code to make a new class FileProcessor2. To do that, first use hg copy to copy it to a new file, then edit that file and change its class name to match the file name.

In the previous lab, you stepped through collections by explicitly creating an instance of Iterator and calling its hasNext() and next methods. That pattern of access is common enough that Java provides a special version of the for statement to do it. For any iterable collection coll with an element type T, you can write a loop as

    for (T x: coll) {
        process element x
    }

Because the body is executed for each element in the collection, this is usually called a for-each loop. Note that coll has to be something that has a method iterator().

Rewrite each of your for loops that processes a collection to use a for-each loop. (You need to be careful with your HashMap, because you can't iterate over the map itself.)

Test your new program and commit it to the repository.

3. StringTokenizer

Sometimes when processing input, you will have a string that you need to break up into pieces--into words, for example. The general term used for such a piece of input is a token.

The Java library provides a class StringTokenizer that can do this breaking up for you. The instance methods for this class resemble those on an iterator:

You get to define what counts as a token when you construct the StringTokenizer:

Take a close look at the method toArrayList() in your program. You will find there the creation of a StringTokenizer and a loop that processes each of the tokens.

There is no code to do for this section. But we will need to be able to use this class in the near future.

4. Turn in

Make a typescript showing your program FileProcessor2 running on one of the sample files given.

Turn in your source files and typescript with a command like

/cslab/class/csci235/bin/handin lab12 *.java typescript

Cary Gray
Last modified: Tue Apr 8 12:33:12 CDT 2014