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 however works fine and as expected, 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());
My Tree class looks like this:
public class Tree<E> implements java.lang.Iterable{
...
public TreeIterator<E> iterator(){
return new TreeIterator<E>(root);//return an iterator for the root node
}
....
}
And my TreeIterator class looks like this:
public class TreeIterator<E> implements java.util.Iterator<E>{
public E next(){
...
}
...
}
But I want to get the for (String s : tree)
loop working properly - any ideas? The whole point of this was to set up a clean foreach loop for use in my program, not to use that ugly for loop.
Any idea what I'm doing wrong?
Edit:
As per the best answer (and another equally good answer which was posted shortly after), the following made it work:
Changing
public class Tree<E> implements java.lang.Iterable{
....
}
to
public class Tree<E> implements java.lang.Iterable<E>{
....
}
...Thanks guys!