Iterator Pattern
Traverse a container and access the container's elements. The iterator pattern decouples algorithm from containers.
主要是call next 的时候,iterator如果现在不valid,需要往前走看是不是valid,但这个时候需要cache当前valid的数据,因为iterator是只能往前走。。。
Goal
Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation. 只能往前走,不能回头,这是思考iterator的关键! 常见trick;next要return什么,把iterator put one step ahead!
Interface Iterator<E> {
boolean hasNext(); //check if we still have some elements in collection, don't proceed if empty
E next(); //proceed to next and return
void remove(); //remove current element, usually you don't need to implement this
}
Another implementation
boolean moveNext(); //proceed to next position
E current(); //return element at current position
Flexible for what ?
provide a view not a copy, not changing internal data structure.
different traversing algorithm can be done on same collection through implementing different iterators without changing internal data structure.