Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.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!

like image 447
CS Student Avatar asked Jul 03 '26 06:07

CS Student


2 Answers

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.

like image 124
fhe Avatar answered Jul 05 '26 19:07

fhe


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

like image 36
Bozho Avatar answered Jul 05 '26 19:07

Bozho



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!