一种模式用于顺序访问集合对象的元素,不需要知道集合对象的底层表示。
Class Diagram
 
Implementation
迭代器接口
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 
 | public interface Iterator<E> {
 
 
 
 boolean hasNext();
 
 
 
 
 
 E next();
 }
 
 | 
迭代器实现类
| 12
 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
 
 | 
 
 
 
 
 public class Dictionary {
 
 private String words[] = {"hello","world","leithda"};
 
 
 public Iterator<String> iterator(){
 return new Itr();
 }
 
 private class Itr implements Iterator<String> {
 int cursor;
 int lastRet = -1;
 
 @Override
 public boolean hasNext() {
 return cursor != words.length;
 }
 
 @Override
 public String next() {
 int i = cursor;
 if(i >= words.length){
 
 }
 cursor = i+1;
 return words[lastRet = i];
 }
 }
 }
 
 | 
测试
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 
 | public class IteratorTest {
 @Test
 public void test() throws Exception{
 Dictionary dictionary = new Dictionary();
 
 Iterator it = dictionary.iterator();
 
 while(it.hasNext()){
 System.out.println(it.next());
 }
 }
 
 }
 
 | 
Example
Refence