I have the tree classes AbstractComponent, Leaf and Composite:
public abstract class AbstractComponent {
privavte String name;
[...]
}
public class Leaf extends AbstractComponent {
[...]
}
public Composite extends AbstractComponent {
private List<AbstractComponent> children;
public void addChild(AbstractComponent a) {
[...]
}
public List<AbstractComponent> getChildren() {
return children;
}
}
My question: How can I write a recursive iterator in Java for a model that is based on the composite pattern? I read this question (Creating a recursive iterator). It is possible to adopt the accepted answer to my problem? I also found the TreeTraverser class from Guava but it seems to be limited to one class that represents a node.
First some help on terminology.
Iterators are not recursive. What you are looking for is a strategy of Tree Traversal.
While tree traversal implementations are often recursive they typically will not be for an iterator.
The structure of your Component objects is called a generic tree.
1st you need to pick how you want to traverse your composite structure (a.k.a Generic Tree)
user1121883's Solution is a great option if you don't have specific traversal order requirements because it is Simple to implement.
If you need to implement a different strategy (e.g. depth first) try the following