迭代器模式(Iterator Pattern)又称为游标模式,它提供一种顺序访问集合/容器元素的方法,而又无须暴露集合内部表示。本质是抽取集合对象迭代的行为到迭代器中,提供一致的访问接口。属于行为型模式。
适用场景:
- 访问一个集合对象的内容而无须保留它的内部表示
- 为遍历不同的集合结构提供一个统一的访问接口
public interface Iterator<E> {
// 检查是否有下一个元素
boolean hasNext();
// 拿到下一个元素
E next();
// remove操作,需实现类去实现
default void remove() {
throw new UnsupportedOperationException("remove");
}
}
ArrayList对Iterator的实现
public class ArrayList<E> {
transient Object[] elementData;
private int size;
private class Itr implements Iterator<E> {
int cursor; // index of next element to return
int lastRet = -1; // index of last element returned; -1 if no such
int expectedModCount = modCount;
public boolean hasNext() {
return cursor != size;
}
public E next() {
checkForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[lastRet = i];
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
}
}
泛型占位符
E: Element, 如果是集合,规定集合元素的类型
T: Type, 规定该类操作的类的具体类型
K: Key, 规定键值对中键的类型
V: Value, 规定键值对中值的类型
?: 任意类型,啥都可以,类似Object