Java Iterators - Trying to get a for each loop to work

Posted by CS Student on Stack Overflow See other posts from Stack Overflow or by CS Student
Published on 2010-03-28T18:31:29Z Indexed on 2010/03/28 18:33 UTC
Read the original article Hit count: 340

Filed under:
|
|
|

So I have a Tree<E> class where E is the datatype held and organized by the tree. I'd like to iterate through the Tree like this, or in a way similar to this:

1.  Tree<String> tree=new Tree<String>();
2.  ...add some nodes...
3.  for (String s : tree)
4.      System.out.println(s);

It gives me an error on line 3 though.

Incompatible types
    required: java.lang.String
    found:    java.lang.Object    

The following works fine and as expected though, performing a proper in-order traversal of the tree and printing each node out as it should:

for (TreeIterator<String> i = tree.iterator(); i.hasNext(); )
    System.out.println(i.next());

Any idea what I'm doing wrong? Do you need to see more of the code?

© Stack Overflow or respective owner

Related posts about homework

Related posts about java