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

标签 java list memory arraylist memory-management

我正在尝试编写有效包装传递给此方法的 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/

相关文章:

java - 如何在命令行中运行maven构建的类

java - 如何将 System.currentMillis 秒转换为 TemporalAccessor

python - 在 Python 中迭代列表的列表

python - 删除列表中连续整数的最快且更有效的方法是什么?

linux - 通过 linux 命令检查主内存使用情况

java - 构造函数与getter和setter的区别

java - 纯 Java ZeroMQ 客户端?

css - 如何使用 Bootstrap 4 在多列中拆分列表?

objective-c - 关于objective-c中setter的一个问题

C++ : Segmentation fault (core dumped) On linux OS