Iterator(迭代器)
作为一种设计模式,迭代器可以用于遍历一个对象,对于这个对象的底层结构开发人员不必去了解。
java中的Iterator一般称为“轻量级”对象,创建它的代价是比较小的。这里笔者不会去考究迭代器这种
设计模式,仅在JDK代码层面上谈谈迭代器的时候以及使用迭代器的好处。
Iterator详解
Iterator是作为一个接口存在的,它定义了迭代器所具有的功能。这里我们就以Iterator接口来看,不考
虑起子类ListIterator。其源码如下:
- package java.util;
- public interface Iterator<E> {
- boolean hasNext();
- E next();
- void remove();
- }
我们以一个实际例子来看。
- List<String> list = new ArrayList<String>();
- list.add("TEST1");
- list.add("TEST2");
- list.add("TEST3");
- list.add("TEST4");
- list.add("TEST6");
- list.add("TEST5");
- Iterator<String> it = list.iterator();
- while(it.hasNext())
- {
- System.out.println(it.next());
- }
list.iterator()好好看看。通过源码了解到该方法产生了一个实现Iterator接口的对象。
- private class Itr implements Iterator<E> {
- 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();
- }
- }
其实这是集合迭代中的一种“快速失败”机制,这种机制提供迭代过程中集合的安全性。阅读源码
就可以知道ArrayList中存在modCount对象,增删操作都会使modCount++,通过两者的对比
迭代器可以快速的知道迭代过程中是否存在list.add()类似的操作,存在的话快速失败!
以一个实际的例子来看,简单的修改下上述代码。
- 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是线程不安全的,如果在使用迭代器的过程中有其他的线程修改了List就会
抛出ConcurrentModificationException这就是Fail-Fast机制。
那么快速失败究竟是个什么意思呢?
在ArrayList类创建迭代器之后,除非通过迭代器自身remove或add对列表结构进行修改,否则在其他
线程中以任何形式对列表进行修改,迭代器马上会抛出异常,快速失败。
迭代器的好处
通过上述我们明白了迭代是到底是个什么,迭代器的使用也十分的简单。现在简要的总结下使用迭代
器的好处吧。
1、迭代器可以提供统一的迭代方式。
2、迭代器也可以在对客户端透明的情况下,提供各种不同的迭代方式。
3、迭代器提供一种快速失败机制,防止多线程下迭代的不安全操作。
不过对于第三点尚需注意的是:就像上述事例代码一样,我们不能保证迭代过程中出现“快速
失败”的都是因为同步造成的,因此为了保证迭代操作的正确性而去依赖此类异常是错误的!
foreach循环
通过阅读源码我们还发现一个Iterable接口。它包含了一个产生Iterator对象的iterator()方法,
而且将Iterator对象呗foreach用来在序列中移动。对于任何实现Iterable接口的对象都可以使用
foreach循环。
foreach语法的冒号后面可以有两种类型:一种是数组,另一种是是实现了Iterable接口的类
对于数组不做讨论,我们看看实现了Iterable的类
- package com.iterator;
- import java.util.Iterator;
- public class MyIterable implements Iterable<String> {
- protected String[] words = ("And that is how "
- + "we know the Earth to be banana-shaped.").split(" ");
- public Iterator<String> iterator() {
- return new Iterator<String>() {
- private int index = 0;
- public boolean hasNext() {
- return index < words.length;
- }
- public String next() {
- return words[index++];
- }
- public void remove() {}
- };
- }
- public static void main(String[] args){
- for(String s:new MyIterable())
- System.out.print(s+",");
- }
And,that,is,how,we,know,the,Earth,to,be,banana-shaped.,