-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDS16_Iterator.java
More file actions
113 lines (80 loc) · 1.83 KB
/
DS16_Iterator.java
File metadata and controls
113 lines (80 loc) · 1.83 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
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
//Iterator
interface Iterator {
Object next();
void first();
void last();
boolean hasNext();
}
//ConcreteIterator
class IteratorImpl implements Iterator {
private List list;
private int index;
public IteratorImpl(List list) {
index = 0;
this.list = list;
}
public void first() {
index = 0;
}
public void last() {
index = list.getSize();
}
public Object next() {
Object obj = list.get(index);
index++;
return obj;
}
public boolean hasNext() {
return index < list.getSize();
}
}
//list
interface List {
Iterator iterator();
Object get(int index);
int getSize();
void add(Object obj);
}
//ConcreteAggregate
class ListImpl implements List {
private Object[] list;
private int index;
private int size;
public ListImpl() {
index = 0;
size = 0;
list = new Object[100];
}
public Iterator iterator() {
return new IteratorImpl(this);
}
public Object get(int index) {
return list[index];
}
public int getSize() {
return this.size;
}
public void add(Object obj) {
list[index++] = obj;
size++;
}
}
//
public class DS16_Iterator{
public static void main(String[] args) {
List list = new ListImpl();
list.add("a");
list.add("b");
list.add("c");
//第一种迭代方式
Iterator it = list.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
System.out.println("=====");
//第二种迭代方式
for (int i = 0; i < list.getSize(); i++) {
System.out.println(list.get(i));
}
}
}