简体   繁体   中英

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

Here is the source code of the next() method in the Iterator provided by ArrayList.iterator() :

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];
}

Why does this code from the JDK try to copy the entire data array elementData into the inner class iterator, since the inner class has access to the fields in the outer class? That will be really expensive for a huge list.

I know there must be an explanation behind this code - what is it?

My question is why JDK try to copy the entire data array into the inner class iterator. That will be really expensive for a huge list.

No, it isn't. It copies the reference to the array, not the array itself. That is always O(1); not expensive at all.

elementData would normally have to be accessed as Itr.outerClass.elementData , with outerClass being the implicit reference the inner class carries to the outer, so this change reduces the number of indirections and references that get followed (by a tiny amount, but it's iterating over an ArrayList , it's one of the most common operations ever).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM