-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCompositeIterator.java
More file actions
46 lines (39 loc) · 1.46 KB
/
CompositeIterator.java
File metadata and controls
46 lines (39 loc) · 1.46 KB
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
package CompositeIteratorPattern;
import java.util.*;
public class CompositeIterator implements Iterator<MenuComponent> {
Stack<Iterator<MenuComponent>> stack = new Stack<Iterator<MenuComponent>>();
// Pass in iterator of the top-level menu
public CompositeIterator(Iterator<MenuComponent> iterator) {
stack.push(iterator);
}
public MenuComponent next() {
if (hasNext()) {
// Get the current iterator off the stack and get its next element
// Stack peek returns the top element without removing it
Iterator<MenuComponent> iterator = stack.peek();
MenuComponent component = iterator.next();
// Then add the iterator of that component to the stack
stack.push(component.createIterator());
return component;
} else {
return null;
}
}
public boolean hasNext() {
if (stack.empty()) {
return false;
} else {
// Get iterator off the top of the stack and see if it has next
Iterator<MenuComponent> iterator = stack.peek();
if (!iterator.hasNext()) {
// if it doesn't, pop it off the stack
stack.pop();
// Recurively call hasNext() to check the next iterator
return hasNext();
} else {
// If it has a next element, return true
return true;
}
}
}
}