gpt4 book ai didi

java - 如果 ArrayList 的大小已传递给构造函数,则添加新元素时,Java 中 ArrayList 的元素是否会在内存中重新分配?

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

我正在尝试编写有效包装传递给此方法的 List 中的每个元素的方法,并返回创建的带有包装元素的 ArrayList

根据documentation :

The size(), isEmpty(), get(), set(), iterator(), and listIterator() operations run in constant time. The add operation runs in amortized constant time, that is, adding n elements requires O(n) time. All of the other operations run in linear time (roughly speaking). The constant factor is low compared to that for the LinkedList implementation.

我的理解是否正确,如果我创建一个 ArrayList 并将初始容量传递给构造函数,ArrayList 中的元素在新建时不会在内存中重新分配添加了哪些?

例子:

public static <T> ArrayList<RequestToExternalSource<T>> wrapExternalSources(List<ExternalSource<T>> externalSources, BiConsumer<Integer, T> publishResult) {
ArrayList<RequestToExternalSource<T>> requests = new ArrayList<>(externalSources.size());

ListIterator<ExternalSource<T>> externalSourcesIterator = externalSources.listIterator();
int index = 0;

while (externalSourcesIterator.hasNext()) {
requests.add(new RequestToExternalSource<>(
index++,
externalSourcesIterator.next(),
publishResult));
}
return requests;
}

最佳答案

要回答这个问题,我们可以直接看ArrayList#add的源码。我们首先看到如下方法:

public boolean add(E e) {
modCount++;
add(e, elementData, size);
return true;
}

上面的方法调用了下面的private,重载了add方法:

private void add(E e, Object[] elementData, int s) {
if (s == elementData.length)
elementData = grow();
elementData[s] = e;
size = s + 1;
}

我们可以看到elementData(保存数据的Object[])只会在s(大小参数,等于到 ArrayList#size 在我们的例子中)等于数据数组的长度。因此,elementData 不会增长,即使我们将 n 元素添加到初始化容量为n,很好!

Do I understand it right that If I create an ArrayList and pass the initial capacity to the constructor, the elements in ArrayList won't be reallocated in memory when new ones are added?

由于这些原因,是的,你是对的,直到你添加的元素超过指定的容量。

关于java - 如果 ArrayList 的大小已传递给构造函数,则添加新元素时,Java 中 ArrayList 的元素是否会在内存中重新分配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48492424/

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