21 Mar 2012 [ 201 week10 ]

On Tuesday we covered several examples of implementing the Iterable and Iterator interfaces (see links in the week 9 post).

Take a look at our examples. Note that the examples are missing a lot of error handling, so in many cases they would not fail gracefully.

Here's the test program that exercises a lot of the classes we worked on (and a couple new pieces I added):

import java.util.ArrayList;
import java.util.Iterator;

public class IterableTest {
    
    // Examples of two equivalent versions of sum method:
    
    public static int sum(Iterable<Integer> list) {
        int total = 0;
        for (int x : list)
            total += x;
        return total;
    }
    
    public static int sum1(Iterable<Integer> list) {
        int total = 0;
        Iterator<Integer> iter = list.iterator();
        while (iter.hasNext())
            total += iter.next();
        return total;
    }
    
    public static void main(String[] args) {
        System.out.println("Print odd numbers <= 10:");
        for (int x : new Odds(new Counter())) {
            System.out.println(x);
            if (x > 10)
                break;
        }
        
        System.out.println("Also works with an ArrayList as input:");
        ArrayList<Integer> numbers = new ArrayList<Integer>();
        numbers.add(0);
        numbers.add(1);
        numbers.add(22);
        numbers.add(5);
        for (int x : new Odds(numbers)) {
            System.out.println(x);
        }

        System.out.println("Print out first 10 odd numbers:");
        // See Iter class for static utility methods.
        Iter.Print(Iter.Take(Iter.Odds(Iter.Counter()), 10));
    }
}