views:

273

answers:

3

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!

+4  A: 

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>)

Bozho
+4  A: 

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.

fhe
Oh - right! That makes sense, that's why it's asking for an `Object`; since right now my `Tree<E>` class is basically implementing `Iterable<Object>`!
CS Student
A: 

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.

Varun Garde
No the iterator returns just one String (or whatever E happens to be) each time next() is called. Thanks though!
CS Student