15-100 Lecture 16 (Tuesday, June 17, 2008)

Collections

Today we talked about some fo the data structures provided to use by the Java class library. In particular, we discussed the List, Map, and Set interfaces as well as the ArrayList, LinkedList, HashMap, TreeMap, HashSet, and TreeSet implementations. We also discussed using an Iterator to walk through a collection.

As this discussion fall under the general category of "Using the API", there aren't notes, in particular. But, there are two good resources:

The for-each loop

Java 5 introduced a new construct for traversing collections: the for-each loop. The for-each loop isn't really a new first-class construct. Instead you can think of it as a really convenient syntax for traversing a data structure using an interator.

Consider the example below. Notice the :-colon. When reading the code, read the :-colon as "in".

  import java.util.*;

  class GenericsExample {


    public static void main(String[] args) {

      List l = new LinkedList();

      l.add ("Hello");
      l.add ("Great");
      l.add("World");

      System.out.println (l);
      System.out.println ((String) l.get(0));


      for (Object word : l ) {
        System.out.println ((String)word);
      }

    }
  }
  

The example above printes each and every item within list l. See how pretty? The for-each loop can basically be used any time you are doing simple traversal. It can't be used when you are mutating the collection within the loop nor can for-each loops be nested. When it comes right down to it, its just a simple "macro" rewritten into standard syntax before the byte code is emitted.