4 package net
.kezvh
.collections
;
6 import java
.util
.Collections
;
7 import java
.util
.Iterator
;
8 import java
.util
.LinkedList
;
13 * @param <T> the type of the tree node
15 public class TreeIterator
<T
> implements Iterator
<T
> {
19 * @param <T> the type of the tree node
21 public interface ChildrenAccessor
<T
> {
24 * @return the children of the node
26 Iterator
<T
> getChildren(T node
);
29 private final ChildrenAccessor
<T
> childrenAccessor
;
31 private final LinkedList
<Iterator
<T
>> iteratorStack
= new LinkedList
<Iterator
<T
>>();
34 * @param rootNode COMMENT
35 * @param childrenAccessor COMMENT
37 public TreeIterator(final T rootNode
, final ChildrenAccessor
<T
> childrenAccessor
) {
38 this.childrenAccessor
= childrenAccessor
;
39 this.iteratorStack
.add(Collections
.singleton(rootNode
).iterator());
43 * @see java.util.Iterator#hasNext()
47 public boolean hasNext() {
48 for (final Iterator
<T
> iterator
: this.iteratorStack
)
49 if (iterator
.hasNext())
55 * @see java.util.Iterator#next()
60 while (!this.last().hasNext())
61 this.iteratorStack
.removeLast(); // will throw a NSEE if hasNext() is false
62 final T nextNode
= this.last().next();
64 final Iterator
<T
> children
= this.childrenAccessor
.getChildren(nextNode
);
65 if (children
.hasNext())
66 this.iteratorStack
.addLast(children
);
71 private Iterator
<T
> last() {
72 return this.iteratorStack
.peekLast();
76 * @see java.util.Iterator#remove()
79 public void remove() {
80 this.iteratorStack
.peekLast().remove();