gpt4 book ai didi

java - 为什么ArrayList的Iterator.next()方法会复制elementData字段?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:37:58 25 4
gpt4 key购买 nike

这里是ArrayList.iterator()提供的Iteratornext()方法的源码:

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 复制到内部类迭代器中,因为内部类可以访问外部类中的字段?对于一个巨大的列表来说,这将是非常昂贵的。

我知道这段代码背后一定有一个解释——它是什么?

最佳答案

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.

不,不是。它将引用 复制到数组,而不是数组本身。那总是 O(1);一点也不贵。

elementData 通常必须作为 Itr.outerClass.elementData 访问,outerClass 是内部类对外部,因此此更改减少了间接寻址和引用的数量(少量减少,但它遍历 ArrayList它是有史以来最常见的操作之一).

关于java - 为什么ArrayList的Iterator.next()方法会复制elementData字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38405223/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com