Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 8b418cf

Browse files
author
deeper
committed
add iterator
1 parent b1e7ee6 commit 8b418cf

File tree

5 files changed

+89
-0
lines changed

5 files changed

+89
-0
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package com.ruoxu.pattern.iterator;
2+
/**
3+
* 迭代器模式(用的少)
4+
* 定义:提供一种方法顺序访问一个容器对象中的各个元素,而不需要暴露该对象的内部表示。
5+
* 总结:C++,Python,Java,PHP等多种语言都有相应的内置实现,对于开发者而言,已经极少自己实现迭代器了。
6+
*/
7+
public class Demo {
8+
public static void main(String[] args) {
9+
MyList<String> list = new MyArrayList<>();
10+
list.add("Alice");
11+
list.add("tom");
12+
13+
MyIterator<String> iterator = list.iterator();
14+
while(iterator.hasNext()){
15+
System.out.println(iterator.next());
16+
}
17+
}
18+
19+
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package com.ruoxu.pattern.iterator;
2+
3+
import java.util.ArrayList;
4+
import java.util.List;
5+
6+
public class MyArrayList<T> implements MyList<T>{
7+
private List<T> list = new ArrayList<>();
8+
9+
@Override
10+
public void add(T t) {
11+
list.add(t);
12+
}
13+
14+
@Override
15+
public void remove(T t) {
16+
list.remove(t);
17+
}
18+
19+
@Override
20+
public MyIterator<T> iterator() {
21+
22+
return new ReaIterator<>(list);
23+
}
24+
25+
}
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
package com.ruoxu.pattern.iterator;
2+
3+
public interface MyIterator<T>{
4+
5+
boolean hasNext();
6+
7+
T next();
8+
9+
}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
package com.ruoxu.pattern.iterator;
2+
3+
public interface MyList<T>{
4+
5+
void add(T t);
6+
7+
void remove(T t);
8+
9+
MyIterator<T> iterator();
10+
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package com.ruoxu.pattern.iterator;
2+
3+
import java.util.List;
4+
5+
public class ReaIterator<T> implements MyIterator<T>{
6+
private List<T> list;
7+
private int index;
8+
9+
public ReaIterator(List<T> list) {
10+
this.list = list;
11+
}
12+
13+
@Override
14+
public boolean hasNext() {
15+
return index != list.size();
16+
}
17+
@Override
18+
public T next() {
19+
T obj = null;
20+
if(hasNext()){
21+
obj = list.get(index++);
22+
}
23+
return obj;
24+
}
25+
26+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /