1package ds.util;
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
30public abstract class Iterator<E>
31 implements java.util.Iterator<E> {
32
33
34
35
36 public void remove() {
37 throw
38 new UnsupportedOperationException
39 ("iterator does not support remove");
40 }
41
42
43
44 public int size() {
45 int res = 0;
46 while ( hasNext() ) {
47 ++res;
48 next();
49 }
50 return
51 res;
52 }
53
54
55
56
57 public <R> R fold(R n, Function2<R,E,R> f) {
58 R res = n;
59 while ( hasNext() ) {
60 E x = next();
61 res = f.apply(res, x);
62 }
63 return
64 res;
65 }
66
67
68
69
70
71 public <R> Iterator<R> map(Function<E,R> f) {
72 return
73 new MapIterator<E,R>(this, f);
74 }
75
76
77
78 public boolean all(Predicate<E> p) {
79 boolean res = true;
80 while ( res && hasNext() ) {
81 res = p.isTrue(next());
82 }
83 return
84 res;
85 }
86
87
88
89 public boolean any(Predicate<E> p) {
90 boolean res = false;
91 while ( ! res && hasNext() ) {
92 res = p.isTrue(next());
93 }
94 return
95 res;
96 }
97
98
99
100
101
102 public String toString() {
103 StringBuffer res = new StringBuffer();
104
105 if ( hasNext() ) {
106 boolean first = true;
107
108 while ( hasNext() ) {
109 E x = next();
110 res.append(first ? "[" : ",");
111 res.append(x);
112 first = false;
113 }
114 } else {
115 res.append("[");
116 }
117 res.append("]");
118
119 return
120 new String(res);
121 }
122}