ListItr

  • ListItr继承于Itr实现ListIterator接口
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    An optimized version of AbstractList.ListItr
    private class ListItr extends Itr implements ListIterator<E> {
    //唯一构造器:把index给cursor
    ListItr(int index) {
    super();
    cursor = index;
    }
    //判断是否有前驱
    public boolean hasPrevious() {
    return cursor != 0;
    }
    //获取当前元素的索引
    public int nextIndex() {
    return cursor;
    }
    获取前驱的索引
    public int previousIndex() {
    return cursor - 1;
    }
    public E previous();
    public void set(E e);
    public void add(E e);
    }

previous()

  • 获取前驱
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    public E previous() {
    checkForComodification();
    int i = cursor - 1;
    if (i < 0)
    throw new NoSuchElementException();
    Object[] elementData = ArrayList.this.elementData;
    if (i >= elementData.length)
    throw new ConcurrentModificationException();
    cursor = i;
    return (E) elementData[lastRet = i];
    }

set(E e)

  • 调用ArrayList.set,其本身不会修改 modCount值
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    public void set(E e) {
    if (lastRet < 0)
    throw new IllegalStateException();
    checkForComodification();

    try {
    ArrayList.this.set(lastRet, e);
    } catch (IndexOutOfBoundsException ex) {
    throw new ConcurrentModificationException();
    }
    }

add(E e)

  • 调用此迭代器的add方法,会导致modCount改变,但此迭代器本身也会让expectedModCount进行重新赋值,所以此时也只有这个迭代器不会失效。
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    public void add(E e) {
    checkForComodification();

    try {
    int i = cursor;
    ArrayList.this.add(i, e);
    cursor = i + 1;
    lastRet = -1;
    expectedModCount = modCount;
    } catch (IndexOutOfBoundsException ex) {
    throw new ConcurrentModificationException();
    }
    }