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();
,下面的遍历程序一样正常运行。