8 boolean hasNext();
9 }
1 /**
2 *
3 * @author LingJian
4 *
5 */
6 public class LinkedList implements Collection {
7 //头
8 private Node head = null;
9 //尾
10 private Node tail = null;
11 private int index = 0;
12
13 public void add(Object o) {
14 Node n = new Node(o,null);
15 if(head == null) {
16 head = n;
17 tail = n;
18 }
19 tail.setNext(n);
20 tail = n;
21 index ++;
22 }
23
24 public int size() {
25 return index;
26 }
27
28 @Override
29 public Iterator iterator() {
30 return new LinkedListIterator();
31 }
32
33 public class LinkedListIterator implements Iterator {
34
35 @Override
36 public Object next() {
37 Object o = head.getData();
39 return o;
40 }
41
42 @Override
43 public boolean hasNext() {
44 if(head == null) return false;
45 else return true;
46 }
47
48 }
49 }
1 /**
2 *
3 * @author LingJian
4 *
5 */
6 public class Test {
7
8 /**
9 * @param args
10 */
11 public static void main(String[] args) {
12 Collection c = new LinkedList();
13 for(int i=0; i<15; i++) {
14 c.add(new Cat(i));
15 };
16 System.out.println(c.size());
17
18
19
20 Iterator it = c.iterator();
21 while(it.hasNext()) {
22 Object o = it.next();
23 System.out.print(o + " ");
24 }
25
26 }
27
28 } 有了Iterator,遍历的聚合对象只要对外提供了自己符合要求的Iterator,这段遍历的方法便可重复使用,完全不需要关注元素的内部结构。
Iterator模式主要用于遍历,所以相对来说比较简单。