首页 | 新闻 | 新品 | 文库 | 方案 | 视频 | 下载 | 商城 | 开发板 | 数据中心 | 座谈新版 | 培训 | 工具 | 博客 | 论坛 | 百科 | GEC | 活动 | 主题月 | 电子展
返回列表 回复 发帖

Java 容器源码分析之 ArrayList(7)

Java 容器源码分析之 ArrayList(7)

迭代在AbstractList中其实已经提供了迭代器的一个实现,ArrayList类中又提供了一个优化后的实现。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/**
* An optimized version of AbstractList.Itr
*/
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();
        }
    }

    @Override
    @SuppressWarnings("unchecked")
    public void forEachRemaining(Consumer<? super E> consumer) {
        Objects.requireNonNull(consumer);
        final int size = ArrayList.this.size;
        int i = cursor;
        if (i >= size) {
            return;
        }
        final Object[] elementData = ArrayList.this.elementData;
        if (i >= elementData.length) {
            throw new ConcurrentModificationException();
        }
        while (i != size && modCount == expectedModCount) {
            consumer.accept((E) elementData[i++]);
        }
        // update once at end of iteration to reduce heap write traffic
        cursor = i;
        lastRet = i - 1;
        checkForComodification();
    }

    final void checkForComodification() {
        if (modCount != expectedModCount)
            throw new ConcurrentModificationException();
    }
}
迭代器中通过一个游标cursor来达到遍历所有元素的目的,同时还保留了上一个访问的位置以便于remove方法的实现。前面说过,ArrayList的实现并不是线程安全,其fail-fast机制的实现是通过modCount变量来实现的。在这里我们可以清楚地看到,在迭代器的next和remove等方法中,首先就会调用checkForComodification方法来判断ArrayList容器是否在迭代器创建后发生过结构上的修改,其具体的实现是通过比较创建迭代器时的modCount(即expectedModCount)和当前modCount是否相同来完成的。如果不相同,表明在此过程中其他线程修改了ArrayList(添加了或移除了元素),会抛出ConcurrentModificationException异常。
List接口还支持另一种迭代器,ListIterator<E>,不仅可以使用next()方法向前迭代,还可以使用previous()方法向后移动游标。ArrayList中也实现了listIterator()和listIterator(int index)方法,比较简单,这里就不再详细说了。
返回列表