-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathiterator.java
84 lines (68 loc) · 1.58 KB
/
iterator.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import java.util.ArrayList;
import java.util.List;
interface Aggregate {
Iterator createIterator();
}
class ConcreteAggregate implements Aggregate {
private List<Object> list = new ArrayList<>();
@Override
public Iterator createIterator() {
return new ConcreteIterator(this);
}
public void add(Object obj){
this.list.add(obj);
}
public void remove(Object obj){
this.list.remove(obj);
}
public int size(){
return this.list.size();
}
public Object get(int idx){
return this.list.get(idx);
}
}
interface Iterator {
Object first();
Object next();
boolean isDone();
Object currentItem();
}
class ConcreteIterator implements Iterator {
private ConcreteAggregate a;
private int idx = 0;
public ConcreteIterator(ConcreteAggregate a) {
this.a = a;
}
@Override
public Object first() {
return a.get(0);
}
@Override
public Object next() {
return a.get(idx++);
}
@Override
public boolean isDone() {
return idx >= a.size();
}
@Override
public Object currentItem() {
return a.get(idx);
}
}
public class Main {
public static void main(String[] args){
ConcreteAggregate a = new ConcreteAggregate();
a.add("test");
a.add(2);
a.add(true);
a.add("test2");
a.add("DD");
Iterator iterator = a.createIterator();
while(!iterator.isDone()){
System.out.println(iterator.currentItem());
iterator.next();
}
}
}