动机:集合内部对象变化,虚妄不暴露内部结构同时让外部代码访问其中元素
class Iterator<T>{
public void first();
public T next();
public boolean hasNext();
public Iterator<T> Iterator();
}
class MyCollection implements Iterator{
@Override
public Iterator<T> Iterator(){
return ...;
}
}
class Test{
public static void main(String [] args){
MyCollection mc=new MyCollection();
Iterator<MyCollection> it=mc.Iterator();
while(it.hasNext()){
....
it.next();
}
}
}
这种迭代器是运行时多态,而不是编译时多态,迭代器还是必须要MyCollection,如果能够让迭代器不依赖具体容器,而依赖一个容器接口,那么将会更加完美
such as:ListIterator