迭代器模式与Java Iterator源码
迭代器模式 迭代器模式是一种将集合的增删改操作与集合的顺序遍历操作分离的设计模式。集合只负责增删改操作,迭代器对于集合的内部类,专门负责顺序遍历。Java的Iterator是迭代器模式的经典实现。笔者jdk版本是11.0.4,不同版本的jdk的Iterator相关类及其实现有所不同,下面以jdk11.0.4为例。 Iterator jdk定义了一个 Iterator 接口,声明了 hasNext , next , remove 方法,分别用于检查是否结束遍历、遍历下一个元素、删除元素的操作。 /** * An iterator over a collection. {@code Iterator} takes the place of * {@link Enumeration} in the Java Collections Framework. Iterators * differ from enumerations in two ways: * * <ul> * <li> Iterators allow the caller to remove elements from the * underlying collection during the iteration with well-defined * semantics. * <li> Method names have