Computer Science 15-100 (Sections T & U), Spring 2008
Class Notes:  Java Collections


Logistics

  1. Schedule
    1. Due tomorrow:  hw9b
    2. Due Friday:  hw9b
    3. Bonus Lecture #4 (Tetris!) makeup:  Monday at 7pm
  2. Reading:
    1. Ch 12 (sort of):  Collections

Topic Outline:

  1. Simple examples:
    // List, Set, and Map examples
    import java.util.*;
    @SuppressWarnings("unchecked")
    public class Foo {
          
      public static void listExample() {
        ArrayList list = new ArrayList();
        list.add("Let's");
        list.add("Go");
        list.add("Pens!");
        verify(list.toString().equals("[Let's, Go, Pens!]"));
      } 
      
      public static void setExample() {
        HashSet set = new HashSet();
        set.add("fred");
        set.add("wilma");
        set.add("barney");
        set.add("fred"); // second "add" of "fred" has no effect
        verify(set.contains("fred") == true);
        verify(set.contains("betty") == false);
    
        ArrayList list = new ArrayList(set);
        // notice two things about the toString call, which
        // demonstrate the key differences between Sets and Lists:
        // 1. "fred" is there only once
        // 2. the order is not necessarily as given
        //    (we added "fred" first, yet "wilma" is first in the toString!)
        verify(list.toString().equals("[wilma, fred, barney]"));
      }
      
      public static void mapExample() {
        HashMap map = new HashMap();
        map.put("fred","flintstone");
        map.put("wilma","flintstone");
        map.put("barney","rubble");
        verify(map.get("fred").equals("flintstone"));
        verify(map.get("betty") == null);
        // change the map for fred
        map.put("fred","astaire");
        verify(map.get("fred").equals("astaire"));
      }
    
      public static void main(String[] args) throws Exception {
        System.out.println("Running examples for list, set, and map:");
        listExample();
        setExample();
        mapExample();
        System.out.println("Passed all tests!");
      }
      
      public static void verify(boolean b) {
        if (!b) throw new RuntimeException("Ack!");
      }
    }
  2. List, Set, and Map iteration examples:
    // List, Set, and Map iteration examples
    import java.util.*;
    @SuppressWarnings("unchecked")
    public class Foo {
          
      public static void listIterationExample1() {
        ArrayList list = new ArrayList();
        list.add("abc");
        list.add("def");
        list.add("ghi");
        String check = "";
        for (int i=0; i<list.size(); i++) {
          String s = (String)list.get(i);
          check += s;
        }
        verify(check.equals("abcdefghi"));
      } 
    
      public static void listIterationExample2() {
        ArrayList list = new ArrayList();
        list.add("abc");
        list.add("def");
        list.add("ghi");
        String check = "";
        Iterator iterator = list.iterator();
        while (iterator.hasNext()) {
          String s = (String)iterator.next();
          check += s;
        }
        verify(check.equals("abcdefghi"));
      }
     
      public static void setIterationExample() {
        HashSet set = new HashSet();
        set.add("abc");
        set.add("def");
        set.add("ghi");
        set.add("abc"); // second "add" of "abc" has no effect
        String check = "";
        Iterator iterator = set.iterator();
        while (iterator.hasNext()) {
          String s = (String)iterator.next();
          check += s;
        }
        verify(check.equals("ghidefabc")); // note the unpredictable order!
      }
      
      public static void mapIterationExample() {
        HashMap map = new HashMap();
        map.put("abc","one");
        map.put("def","one");
        map.put("ghi","two");
    
        // Here is how you iterate over the keys:
        String keysCheck = "";
        Iterator keysIterator = map.keySet().iterator();
        while (keysIterator.hasNext()) {
          String s = (String)keysIterator.next();
          keysCheck += s;
        }
        verify(keysCheck.equals("ghidefabc")); // <- unpredictable order!
    
        // And here is how you iterate over the values
        String valuesCheck = "";
        Iterator valuesIterator = map.values().iterator();
        while (valuesIterator.hasNext()) {
          String s = (String)valuesIterator.next();
          valuesCheck += s;
        }
        verify(valuesCheck.equals("twooneone")); // <- unpredictable order!
      }
    
      public static void main(String[] args) throws Exception {
        System.out.println("Running examples for list, set, and map:");
        listIterationExample1();
        listIterationExample2();
        setIterationExample();
        mapIterationExample();
        System.out.println("Passed all tests!");
      }
      
      public static void verify(boolean b) {
        if (!b) throw new RuntimeException("Ack!");
      }
    }
  3. Enhanced "for" loop ("foreach" loop)
    // Enhanced "for" loop ("foreach" loop) example
    import java.util.*;
    @SuppressWarnings("unchecked")
    public class Foo {
    
      public static void foreachExampleWithArray() {
        String[] array = { "abc", "def", "ghi" };
        String check = "";
        for (String s : array)
          check += s;
        verify(check.equals("abcdefghi"));
      } 
    
      public static void foreachExampleWithoutGenerics() {
        ArrayList list = new ArrayList();
        list.add("abc");
        list.add("def");
        list.add("ghi");
        String check = "";
        for (Object obj : list) {
          String s = (String) obj; // must cast from "Object" to "String"
          check += s;
        }
        verify(check.equals("abcdefghi"));
      } 
    
      public static void foreachExampleWithGenerics() {
        ArrayList<String> list = new ArrayList<String>();
        list.add("abc");
        list.add("def");
        list.add("ghi");
        String check = "";
        for (String s : list) {  // no need to cast!
          check += s;
        }
        verify(check.equals("abcdefghi"));
      } 
    
      public static void main(String[] args) throws Exception {
        System.out.println("Running examples for 'foreach' loop:");
        foreachExampleWithArray();
        foreachExampleWithoutGenerics();
        foreachExampleWithGenerics();
        System.out.println("Passed all tests!");
      }
      
      public static void verify(boolean b) {
        if (!b) throw new RuntimeException("Ack!");
      }
    }
  4. Some List (ArrayLists) methods
  5. Set and HashSet
  6. Map and HashMap
     
  7. Queue (List), Stack, and PriorityQueue
     
  8. Arrays class
     
  9. Collections class
     
  10. Generics

carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem