Iterator主要針對Java容器設計的,主要目的就是爲了解決多種容器統一遍歷的問題。每一種容器都有其獨特的遍歷方式,當使用的容器發生變化的時候,遍歷部分的代碼也要跟着變化,這樣不便於程序的維護,使用Iterator將使程序更加靈活。廢話少說,直接上代碼,程序員還是代碼更有說明性。代碼實現了ArrayList與LinkedList兩種容器的邏輯。
下面代碼實現了這兩種容器處理元素時經常用到的兩種方法add()和size()。爲了統一容器的調用方法規範,所以讓兩個容器都實現Collection接口,也就是面向接口的編程了,一類或幾類事物的共同特徵都可以用接口。
Collection接口代碼如下:
public interface Collection {
void add(Object o);
int size();
Iterator iterator();
}
自定義的ArrayList 容器代碼如下:
public class ArrayList implements Collection {
Object[] objects = new Object[10];
int index = 0;
public void add(Object o) {
if(index == objects.length) {
Object[] newObjects = new Object[objects.length * 2];
System.arraycopy(objects, 0, newObjects, 0, objects.length);
objects = newObjects;
}
objects[index] = o;
index ++;
}
public int size() {
return index;
}
}
自定義的LinkedList 容器代碼如下:
public class LinkedList implements Collection {
Node head = null;
Node tail = null;
int size = 0;
public void add(Object o) {
Node n = new Node(o, null);
if(head == null) {
head = n;
tail = n;
}
tail.setNext(n);
tail = n;
size ++;
}
public int size() {
return size;
}
@Override
public Iterator iterator() {
return null;
}
}
public class Node {
public Node(Object data, Node next) {
super();
this.data = data;
this.next = next;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
private Object data;
private Node next;
}
上面兩種容器數據結構一個是數組,一個是鏈表,遍歷方式明顯不同,所以加入Iterator接口,代碼如下:
public interface Iterator {
Object next();
boolean hasNext();
}
這樣只要容器內部實現Iterator,並實現裏面的next()和hasNext()方法即可,在ArrayList類中添加如下代碼:
public Iterator iterator() {
return new ArrayListIterator();
}
private class ArrayListIterator implements Iterator {
private int currentIndex = 0;
@Override
public boolean hasNext() {
if(currentIndex >= index) return false;
else return true;
}
@Override
public Object next() {
Object o = objects[currentIndex];
currentIndex ++;
return o;
}
}
LinkedList類中實現類似,這樣統一的遍歷方法就實現了,測試代碼如下:
public class Cat {
public Cat(int id) {
super();
this.id = id;
}
private int id;
@Override
public String toString() {
return "cat:" + id;
}
}
public class Test {
public static void main(String[] args) {
//ArrayList al = new ArrayList();
//LinkedList al = new LinkedList();
Collection c = new ArrayList();
for(int i=0; i<15; i++) {
c.add(new Cat(i));
}
System.out.println(c.size());
Iterator it = c.iterator();
while(it.hasNext()) {
Object o = it.next();
System.out.print(o + " ");
}
}
}
這樣Collection c = new ArrayList();
這行代碼換成 Collection c = new LinkedList();
,下面的遍歷程序一樣正常運行。