开发者

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

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.Iterabl开发者_运维知识库e{
    ...
    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!


The foreach loop should be working fine if your Tree<E> class also implements the Iterable<E> interface. You need to make sure that your Iterator also returns the generic type E.


Your Tree has to implement Iterable<E> if you want it to work with the for each loop in a generic way (and hence your iterator() method must return Iterator<E>)


The for loop in the code you pasted :

3. for (String s : tree)

is wrongly typecasting elements of tree dataStructure to a collection (or array) of strings.

I suspect it should look something like:

for (String s : tree.getNodes()){...}

Where getNodes returns a collection of Strings.

Couldn't say though for sure, until you paste more of the code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜