簡體   English   中英

為什么ArrayList的Iterator.next()方法復制elementData字段?

[英]Why does the Iterator.next() method of ArrayList copy the elementData field?

以下是ArrayList.iterator()提供的Iterator next()方法的源代碼:

public E next() {
    checkForComodification();
    int i = cursor;
    if (i >= size)
        throw new NoSuchElementException();

    // Why copy the entire elementData from the outer ArrayList class?
    Object[] elementData = ArrayList.this.elementData;

    if (i >= elementData.length)
        throw new ConcurrentModificationException();
    cursor = i + 1;
    return (E) elementData[lastRet = i];
}

為什么來自JDK的代碼嘗試將整個數據數組elementData復制到內部類迭代器中,因為內部類可以訪問外部類中的字段? 這對於一個龐大的列表來說真的很貴。

我知道這段代碼背后一定有解釋 - 它是什么?

我的問題是為什么JDK嘗試將整個數據數組復制到內部類迭代器中。 這對於一個龐大的列表來說真的很貴。

不,不是。 它復制對數組的引用 ,而不是數組本身。 那總是O(1); 一點都不貴。

elementData通常必須作為Itr.outerClass.elementData進行訪問,其中outerClass是內部類攜帶到外部的隱式引用,因此這種更改減少了后續跟蹤的次數和引用次數(少量,但它正在迭代在ArrayList它是有史以來最常見的操作之一)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM