ArrayList的Iterator()方法理解

ArrayList有兩種迭代器實現,都是按照索引查找,但比正常for循環多了併發操作的安全校驗:
1. Itr()的實現,主要功能-後序遍歷next()方法
public Iterator<E> iterator() {
    return new Itr();
}
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];
}
其中i >= elementData.length的校驗非常疑惑,理論上elementData的擴容的等操作size應該小於elementData.length,不知道在什麼併發場景下會觸發??
public void remove() {
    if (lastRet < 0)
        throw new IllegalStateException();  // 調用remove()方法前,必須調用next()方法,給lastRet賦值
    checkForComodification();

    try {
        ArrayList.this.remove(lastRet);
        cursor = lastRet;
        lastRet = -1;  // 重置索引位
        expectedModCount = modCount;  // 重置modify次數,因此在iterator方法中,不能使用remove(object)
    } catch (IndexOutOfBoundsException ex) {
        throw new ConcurrentModificationException();
    }
}

2. ListIterator繼承自Itr類,主要功能擴展-前序遍歷previous(), set()以及add()方法
public ListIterator<E> listIterator() {
    return new ListItr(0);
}
public ListIterator<E> listIterator(int index) {
    if (index < 0 || index > size)  // 前序遍歷第一個元素cursor - 1
        throw new IndexOutOfBoundsException("Index: "+index);
    return new ListItr(index);
}
ListItr(int index) {
    super();
    cursor = index;  // 初始值範圍 [0, size]
}
public E previous() {
    checkForComodification();
    int i = cursor - 1;  // 對比和Itr迭代的區別
    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];
}
 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章