Iterator源码剖析



让我们来看看AbstracyList如何创建Iterator。首先AbstractList定义了一个内部类(inner class):

    private class Itr implements Iterator {
            ...
            }
            

而iterator()方法的定义是:

    public Iterator iterator() {
            return new Itr();
            }
            

因此客户端不知道它通过Iterator it = a.iterator();所获得的Iterator的真正类型。

现在我们关心的是这个申明为private的Itr类是如何实现遍历AbstractList的:

    private class Itr implements Iterator {
            int cursor = 0;
            int lastRet = -1;
            int expectedModCount = modCount;
            }
            

Itr类依靠3个int变量(还有一个隐含的AbstractList的引用)来实现遍历,cursor是下一次next()调用时元素的位置,第一次调用next()将返回索引为0的元素。lastRet记录上一次游标所在位置,因此它总是比cursor少1。

变量cursor和集合的元素个数决定hasNext():

    public boolean hasNext() {
            return cursor != size();
            }
            

方法next()返回的是索引为cursor的元素,然后修改cursor和lastRet的值:

    public Object next() {
            checkForComodification();
            try {
            Object next = get(cursor);
            lastRet = cursor++;
            return next;
            } catch(IndexOutOfBoundsException e) {
            checkForComodification();
            throw new NoSuchElementException();
            }
            }
            

expectedModCount表示期待的modCount值,用来判断在遍历过程中集合是否被修改过。AbstractList包含一个modCount变量,它的初始值是0,当集合每被修改一次时(调用add,remove等方法),modCount加1。因此,modCount如果不变,表示集合内容未被修改。

Itr初始化时用expectedModCount记录集合的modCount变量,此后在必要的地方它会检测modCount的值:

    final void checkForComodification() {
            if (modCount != expectedModCount)
            throw new ConcurrentModificationException();
            }
            

如果modCount与一开始记录在expectedModeCount中的值不等,说明集合内容被修改过,此时会抛出ConcurrentModificationException。

这个ConcurrentModificationException是RuntimeException,不要在客户端捕获它。如果发生此异常,说明程序代码的编写有问题,应该仔细检查代码而不是在catch中忽略它。

但是调用Iterator自身的remove()方法删除当前元素是完全没有问题的,因为在这个方法中会自动同步expectedModCount和modCount的值:

    public void remove() {
            ...
            AbstractList.this.remove(lastRet);
            ...
            // 在调用了集合的remove()方法之后重新设置了expectedModCount:
            expectedModCount = modCount;
            ...
            }
            

要确保遍历过程顺利完成,必须保证遍历过程中不更改集合的内容(Iterator的remove()方法除外),因此,确保遍历可靠的原则是只在一个线程中使用这个集合,或者在多线程中对遍历代码进行同步。

最后给个完整的示例:

    Collection c = new ArrayList();
            c.add("abc");
            c.add("xyz");
            for(Iterator it = c.iterator(); it.hasNext(); ) {
            String s = (String)it.next();
            System.out.println(s);
            }
            

让我们来看看AbstracyList如何创建Iterator。首先AbstractList定义了一个内部类(inner class):

    private class Itr implements Iterator {
            ...
            }
            

而iterator()方法的定义是:

    public Iterator iterator() {
            return new Itr();
            }
            

因此客户端不知道它通过Iterator it = a.iterator();所获得的Iterator的真正类型。

现在我们关心的是这个申明为private的Itr类是如何实现遍历AbstractList的:

    private class Itr implements Iterator {
            int cursor = 0;
            int lastRet = -1;
            int expectedModCount = modCount;
            }
            

Itr类依靠3个int变量(还有一个隐含的AbstractList的引用)来实现遍历,cursor是下一次next()调用时元素的位置,第一次调用next()将返回索引为0的元素。lastRet记录上一次游标所在位置,因此它总是比cursor少1。

变量cursor和集合的元素个数决定hasNext():

    public boolean hasNext() {
            return cursor != size();
            }
            

方法next()返回的是索引为cursor的元素,然后修改cursor和lastRet的值:

    public Object next() {
            checkForComodification();
            try {
            Object next = get(cursor);
            lastRet = cursor++;
            return next;
            } catch(IndexOutOfBoundsException e) {
            checkForComodification();
            throw new NoSuchElementException();
            }
            }
            

expectedModCount表示期待的modCount值,用来判断在遍历过程中集合是否被修改过。AbstractList包含一个modCount变量,它的初始值是0,当集合每被修改一次时(调用add,remove等方法),modCount加1。因此,modCount如果不变,表示集合内容未被修改。

Itr初始化时用expectedModCount记录集合的modCount变量,此后在必要的地方它会检测modCount的值:

    final void checkForComodification() {
            if (modCount != expectedModCount)
            throw new ConcurrentModificationException();
            }
            

如果modCount与一开始记录在expectedModeCount中的值不等,说明集合内容被修改过,此时会抛出ConcurrentModificationException。

这个ConcurrentModificationException是RuntimeException,不要在客户端捕获它。如果发生此异常,说明程序代码的编写有问题,应该仔细检查代码而不是在catch中忽略它。

但是调用Iterator自身的remove()方法删除当前元素是完全没有问题的,因为在这个方法中会自动同步expectedModCount和modCount的值:

    public void remove() {
            ...
            AbstractList.this.remove(lastRet);
            ...
            // 在调用了集合的remove()方法之后重新设置了expectedModCount:
            expectedModCount = modCount;
            ...
            }
            

要确保遍历过程顺利完成,必须保证遍历过程中不更改集合的内容(Iterator的remove()方法除外),因此,确保遍历可靠的原则是只在一个线程中使用这个集合,或者在多线程中对遍历代码进行同步。

最后给个完整的示例:

    Collection c = new ArrayList();
            c.add("abc");
            c.add("xyz");
            for(Iterator it = c.iterator(); it.hasNext(); ) {
            String s = (String)it.next();
            System.out.println(s);
            }
            

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值