迭代器

  • ArrayList有返回迭代器的方法

    1
    2
    3
    public Iterator<E> iterator() {
    return new Itr();
    }
  • Itr实现Iterator接口

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    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;

    // prevent creating a synthetic constructor
    Itr() {}

    public boolean hasNext(); //判断是否还有值
    public E next()//返回下一个
    public void remove()//删除
    public void forEachRemaining();
    final void checkForComodification();

hasNext()

  • 只要cursor不等于size还存在元素
    1
    2
    3
    public boolean hasNext() {
    return cursor != size;
    }

next()

  • cursor一开始默认是0的,在数组的首元素开始
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
     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];
    }

remove()

1
2
3
4
5
6
7
8
9
10
11
12
13
  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();
}
}

forEachRemaining()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Override
public void forEachRemaining(Consumer<? super E> action) {
Objects.requireNonNull(action);
final int size = ArrayList.this.size;
int i = cursor;
if (i < size) {
final Object[] es = elementData;
if (i >= es.length)
throw new ConcurrentModificationException();
for (; i < size && modCount == expectedModCount; i++)
action.accept(elementAt(es, i));
// update once at end to reduce heap write traffic
cursor = i;
lastRet = i - 1;
checkForComodification();
}
}

checkForComodification()

  • modCount只要不被修改,代表原来容器没被修改,那么使用已经创建的迭代器进行操作也是允许的
    1
    2
    3
    4
    final void checkForComodification() {
    if (modCount != expectedModCount)
    throw new ConcurrentModificationException();
    }