-
Notifications
You must be signed in to change notification settings - Fork 23
/
CompositeIterator.java
58 lines (51 loc) · 1.67 KB
/
CompositeIterator.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package MenuCompositeWithIterator;
import java.util.Iterator;
import java.util.Stack;
/**
* iterating over the MenuItems in the component
* and making sure all the child Menus are included
* @author stefano
*/
public class CompositeIterator implements Iterator {
Stack stack = new Stack();
public CompositeIterator(Iterator iterator) {
// throw the iterator of the top level composite in a stack data structure
stack.push(iterator);
}
public Object next() {
if (hasNext()) {
Iterator iterator = (Iterator)stack.peek();
// if there is a next element, we get the current iterator off the stack
// and get its next element
MenuComponent component = (MenuComponent)iterator.next();
if (component instanceof Menu) {
// if that element is a menu, we have another composite
// so we throw it on the stack
stack.push(component.createIterator());
}
return component;
} else {
return null;
}
}
public boolean hasNext() {
if (stack.empty()) {
return false;
} else {
// we get the iterator off the top of the stack
// and see if it has a next element
Iterator iterator = (Iterator)stack.peek();
// recursive call
if (!iterator.hasNext()) {
stack.pop();
return hasNext();
} else {
return true;
}
}
}
// we're not supporting remove
public void remove() {
throw new UnsupportedOperationException();
}
}