a whole bunch of stuff
[ephemerata.git] / KezvhLib / src-lib / net / kezvh / collections / TreeIterator.java
blob0eeafffe4293a3f1a5bbf3f281fba9c183e09aba
1 /**
3 */
4 package net.kezvh.collections;
6 import java.util.Collections;
7 import java.util.Iterator;
8 import java.util.LinkedList;
10 /**
11 * @author afflux
13 * @param <T> the type of the tree node
15 public class TreeIterator<T> implements Iterator<T> {
16 /**
17 * @author afflux
19 * @param <T> the type of the tree node
21 public interface ChildrenAccessor<T> {
22 /**
23 * @param node
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>>();
33 /**
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());
42 /**
43 * @see java.util.Iterator#hasNext()
44 * @return x
46 @Override
47 public boolean hasNext() {
48 for (final Iterator<T> iterator : this.iteratorStack)
49 if (iterator.hasNext())
50 return true;
51 return false;
54 /**
55 * @see java.util.Iterator#next()
56 * @return x
58 @Override
59 public T 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);
68 return nextNode;
71 private Iterator<T> last() {
72 return this.iteratorStack.peekLast();
75 /**
76 * @see java.util.Iterator#remove()
78 @Override
79 public void remove() {
80 this.iteratorStack.peekLast().remove();