java - 在 Java 8 中,为什么 ArrayList 的默认容量现在为零?

标签 java arraylist java-8

我记得在 Java 8 之前,ArrayList 的默认容量是 10。

令人惊讶的是,默认(void)构造函数的注释仍然说:构造一个初始容量为10的空列表。

来自ArrayList.java:

/**
 * Shared empty array instance used for default sized empty instances. We
 * distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when
 * first element is added.
 */
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

...

/**
 * Constructs an empty list with an initial capacity of ten.
 */
public ArrayList() {
    this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}

最佳答案

从技术上讲,它是 10,而不是零,如果您承认支持数组的延迟初始化。见:

public boolean add(E e) {
    ensureCapacityInternal(size + 1);
    elementData[size++] = e;
    return true;
}

private void ensureCapacityInternal(int minCapacity) {
    if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
        minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
    }

    ensureExplicitCapacity(minCapacity);
}

在哪里

/**
 * Default initial capacity.
 */
private static final int DEFAULT_CAPACITY = 10;

您所指的只是在所有最初为空的 ArrayList 对象之间共享的零大小的初始数组对象。 IE。 10 的容量得到保证lazily,Java 7 中也存在这种优化。

诚然,构造函数契约(Contract)并不完全准确。也许这就是这里困惑的根源。

背景

这是 Mike Duigou 的电子邮件

I have posted an updated version of the empty ArrayList and HashMap patch.

http://cr.openjdk.java.net/~mduigou/JDK-7143928/1/webrev/

This revised implementation introduces no new fields to either class. For ArrayList the lazy allocation of the backing array occurs only if the list is created at default size. According to our performance analysis team, approximately 85% of ArrayList instances are created at default size so this optimization will be valid for an overwhelming majority of cases.

For HashMap, creative use is made of the threshold field to track the requested initial size until the bucket array is needed. On the read side the empty map case is tested with isEmpty(). On the write size a comparison of (table == EMPTY_TABLE) is used to detect the need to inflate the bucket array. In readObject there's a little more work to try to choose an efficient initial capacity.

From: http://mail.openjdk.java.net/pipermail/core-libs-dev/2013-April/015585.html

关于java - 在 Java 8 中,为什么 ArrayList 的默认容量现在为零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34250207/

相关文章:

java - 将二维 ArrayList 添加到三维 ArrayList 作为值传递

performance - 优化插入列表中间

java - 为什么我在尝试打印整数数组时收到 "[Ljava.lang.Integer;@72608760"

java - 如何重构从属性文件中读取的所谓常量值

java - 日期时间解析异常 : Text could not be parsed at index 2

根据参数指定的 Java 对象转换

java - 带有 not 的高级正则表达式

java - 及时建模对象状态变化的最佳实践?

java - 如何从后端获取java Web应用程序中的用户位置?

java - 为什么不链接 java.util.stream.Stream#forEach