001package headfirst.composite.menuiterator;
002
003
004import java.util.Iterator;
005import java.util.Stack;
006
007@SuppressWarnings("rawtypes")
008public class CompositeIterator implements Iterator {
009        Stack<Object> stack = new Stack<Object>();
010
011        public CompositeIterator(Iterator iterator) {
012                stack.push(iterator);
013        }
014
015        public Object next() {
016                if (hasNext()) {
017                        Iterator iterator = (Iterator) stack.peek();
018                        MenuComponent component = (MenuComponent) iterator.next();
019                        if (component instanceof Menu) {
020                                stack.push(component.createIterator());
021                        }
022                        return component;
023                } else {
024                        return null;
025                }
026        }
027
028        public boolean hasNext() {
029                if (stack.empty()) {
030                        return false;
031                } else {
032                        Iterator iterator = (Iterator) stack.peek();
033                        if (!iterator.hasNext()) {
034                                stack.pop();
035                                return hasNext();
036                        } else {
037                                return true;
038                        }
039                }
040        }
041
042        public void remove() {
043                throw new UnsupportedOperationException();
044        }
045}
046
047