CIT 594 Java 5.0 Generics, etc.
Spring 2006, David Matuszek

I'm still learning about generics myself, so here are some of my observations:

If children() returns Iterator<Tree>, then the following works:

        Iterator<Tree> iter = tree.children();
while (iter.hasNext()) {
System.out.println(iter.next().value);
}

The following code does not work, but fails in a bizarre way:

        while (tree.children().hasNext()) {
System.out.println(iter.next().value);
}

I would expect that the call to tree.children() would produce a new iterator each time, so that next() would give the same first element forever. However, what actually happens is that the loop iterates over the children, then "runs off the end" with a NoSuchElementException. I don't know why.

As far as I can tell, there is no way to use the new "enhanced" for loop with an Iterator; it requires an Iterable.


If children() were to return an Iterable<Tree> (such as, for example, returning an ArrayList<Tree>) rather than an Iterator<Tree>, then the following code works:

        Iterator<Tree> iter = tree.children().iterator();
while (iter.hasNext()) {
System.out.println(iter.next().value);
}

As far as I can tell, the following should work, but doesn't:

        for (Tree myTree : tree.children()) {
System.out.println(myTree.value);
} Type mismatch: cannot convert from element type Object to Tree

The enhanced for loop can be made to work:

        for (Object obj : tree.children()) {
Tree myTree = (Tree)obj;
System.out.println(myTree.value);
}
or
        Iterable<Tree> iter = tree.children();
for (Tree myTree : iter) {
System.out.println(myTree.value);
}

or even

        for (Tree myTree : (Iterable<Tree>)tree.children()) {
System.out.println(myTree.value);
}