Java Iterators - Trying to get a for each loop to work
- by CS Student
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?