01: package org.antlr.stringtemplate.language;
02:
03: import java.util.Iterator;
04:
05: /** Given an iterator, return only the non-null elements via next(). */
06: public class StripIterator implements Iterator {
07: protected Iterator it;
08:
09: /** To know if stripped iterator hasNext(), we need to see if there
10: * is another non-null element or not.
11: */
12: protected Object lookahead;
13:
14: public StripIterator(Iterator it) {
15: this .it = it;
16: consume(); // prime lookahead
17: }
18:
19: /** Set lookahead to next non-null element or null if nothing left */
20: protected void consume() {
21: if (!it.hasNext()) {
22: lookahead = null;
23: return;
24: }
25: Object e = null;
26: // scan for next non-null value
27: while (e == null && it.hasNext()) {
28: e = it.next();
29: }
30: lookahead = e;
31: }
32:
33: /** Either the list has more stuff or our lookahead has last element */
34: public boolean hasNext() {
35: return lookahead != null;
36: }
37:
38: public Object next() {
39: Object v = lookahead;
40: consume();
41: return v;
42: }
43:
44: public void remove() {
45: throw new RuntimeException(
46: "unimplemented method: StripIterator remove()");
47: }
48:
49: /** The result of asking for the string of an iterator is the list of elements
50: * and so this is just the list w/o nulls. This is destructive
51: * in that the iterator cursors have moved to the end after printing.
52: */
53: public String toString() {
54: StringBuffer buf = new StringBuffer();
55: while (this.hasNext()) {
56: buf.append(this.next());
57: }
58: return buf.toString();
59: }
60: }
|