Java迭代器深入理解及使用(一)

2014-11-24 09:09:51 · 作者: · 浏览: 2
Iterator(迭代器)
作为一种设计模式,迭代器可以用于遍历一个对象,对于这个对象的底层结构开发人员不必去了解。
java中的Iterator一般称为“轻量级”对象,创建它的代价是比较小的。这里笔者不会去考究迭代器这种
设计模式,仅在JDK代码层面上谈谈迭代器的时候以及使用迭代器的好处。
Iterator详解
Iterator是作为一个接口存在的,它定义了迭代器所具有的功能。这里我们就以Iterator接口来看,不考
虑起子类ListIterator。其 源码如下:
[java]
package java.util;
public interface Iterator {
boolean hasNext();
E next();
void remove();
}
对于这三个方法所实现的功能,字面意义就是了。不过貌似对迭代器的工作“过程”还是迷雾,接下来
我们以一个实际例子来看。
[java] view plaincopy
List list = new ArrayList();
list.add("TEST1");
list.add("TEST2");
list.add("TEST3");
list.add("TEST4");
list.add("TEST6");
list.add("TEST5");
Iterator it = list.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
这段代码的输出结果不用多说,这里的it更像是“游标”,不过这游标具体做了啥,我们还得通过
list.iterator()好好看看。通过源码了解到该方法产生了一个实现Iterator接口的对象。
[java]
private class Itr implements Iterator {
int cursor = 0;
int lastRet = -1;
int expectedModCount = modCount;
public boolean hasNext() {
return cursor != size();
}
public E next() {
checkForComodification();
try {
int i = cursor;
E next = get(i);
lastRet = i;
cursor = i + 1;
return next;
} catch (IndexOutOfBoundsException e) {
checkForComodification();
throw new NoSuchElementException();
}
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
AbstractList.this.remove(lastRet);
if (lastRet < cursor)
cursor--;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException e) {
throw new ConcurrentModificationException();
}
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
对于上述的代码不难看懂,有点疑惑的是int expectedModCount = modCount;这句代码
其实这是集合迭代中的一种“快速失败”机制,这种机制提供迭代过程中集合的安全性。 阅读源码
就可以知道ArrayList中存在modCount对象,增删操作都会使modCount++,通过两者的对比
迭代器可以快速的知道迭代过程中是否存在list.add()类似的操作,存在的话快速失败!
以一个实际的例子来看,简单的修改下上述代码。
[java]
while(it.hasNext())
{
System.out.println(it.next());
list.add("test");
}
这就会抛出一个下面的异常,迭代终止。
对于快速失败机制以前文章中有总结,现摘录过来:
Fail-Fast(快速失败)机制
仔细观察上述的各个方法,我们在源码中就会发现一个特别的属性modCount,API解释如下:
The number of times this list has been structurally modified. Structural modifications are those
that change the size of the list, or otherwise perturb it in such a fashion that iterations in progress
may yield incorrect results.
记录修改此列表的次数:包括改变列表的结构,改变列表的大小,打乱列表的顺序等使正在进行
迭代产生错误的结果。Tips:仅仅设置元素的值并不是结构的修改
我们知道的是ArrayList是线程