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())) {
            if (x > 10)
        System.out.println("Also works with an ArrayList as input:");
        ArrayList<Integer> numbers = new ArrayList<Integer>();
        for (int x : new Odds(numbers)) {

        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));