我们首先来看维基百科的解释,迭代器模式是一种设计模式,是一种最简单也最常见的设计模式。它可以让使用者透过特定的接口遍历容器中的每一个元素而不用了解底层的运作情况。
在java中存在两个接口
public interface Iterator<E>
以及它的子接口
public interface ListIterator<E>
我们以ArrayList为例,观察一下她的实现,以下是迭代器的核心代码
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;
}
@SuppressWarnings("unchecked")
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();
}
}
// 检查并发的修改 由于整个迭代器就不是线程安全的,所以这个并不可靠
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
}
private class ListItr extends Itr implements ListIterator<E> {
ListItr(int index) {
super();
cursor = index;
}
public boolean hasPrevious() {
return cursor != 0;
}
public int nextIndex() {
return cursor;
}
public int previousIndex() {
return cursor - 1;
}
@SuppressWarnings("unchecked")
public E previous() {
checkForComodification();
int i = cursor - 1;
if (i < 0)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i;
return (E) elementData[lastRet = i];
}
public void set(E e) {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.set(lastRet, e);
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
public void add(E e) {
checkForComodification();
try {
int i = cursor;
ArrayList.this.add(i, e);
cursor = i + 1;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
}
代码中出现了我们熟悉的单词cursor,索引,对就是它,这个数组序列的迭代器就可以想象成在一组数据列表中来回移动,检索。抛开checkForComodification();检查并发修改数据结构的检查外,整个的迭代机制并不神秘。
迭代器模式抽象出了几个概念,第一个 最后一个 上一个 下一个 有没有元素,想象一下我们在火车站排队买票,售票员面对整个队伍可不会报出第一个 第二个。。。,而是常说下一个,因为对于她来说每个元素的位置对她来说可以忽略,她只需要处理当前元素,处理下一个元素,当然上一个处理出错,她也会说上一个,比如我找错钱了,而不会记住说第n个出错,没必要 也不需要。