public interface Iterator {
Object next();
boolean hasNext();
}
public interface Collection {
void add(Object o);
int size();
Iterator iterator();
}
实现:
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;
}
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;
}
}
}
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 + " ");
}
}
}
总结:提供一个方法顺序访问一个聚合对象的各个元素,而又不需要暴露该对象的内部表示,容器List自己实现了Iterator类的对象,而具体实现外部并不用关心。