JDK API ArrayList 构造函数的文档不正确。那是一个错误吗?

JDK API documentation is incorrect for ArrayList constructor. Is that a bug?

JDK ArrayList constructor 的文档说初始容量是 10。

这实际上是错误的,因为在列表中添加内容之前,初始容量为 0。我检查了Open JDK的来源以及JDK.

附带的src.zip

我知道这是一项性能优化,但这会被视为错误吗?

仅适用于 JDK 最多 6

这不是错误。

用于存储列表元素的内部数组的初始容量真的是10

这并不意味着列表的大小是10。只是创建了一个大小为10的空数组。

当一个对象被添加到列表中时,指向最后一个元素的内部指针被移动一个。如果数组的容量不足,则创建另一个容量更大的数组,并将旧数组复制到新数组的第一部分。此时数组的容量还不到10

密码是:

public ArrayList() {
    this(10);   // Here the 10 of the default capacity
}

public ArrayList(int initialCapacity) {
    super();
    if (initialCapacity < 0)
        throw new IllegalArgumentException("Illegal Capacity: "+
                                                initialCapacity);
    this.elementData = new Object[initialCapacity];
}

较新的 JDK(来自 java 1.7)

重要提示: 是的,在 ArrayList 的较新版本中(我认为来自 Java7)源代码已更改文档仍然是旧文档。所以是的 这是文档中的错误

这里是新版本的构造函数

private static final Object[] EMPTY_ELEMENTDATA = {};

....

public ArrayList() {
    super();
    this.elementData = EMPTY_ELEMENTDATA;  // This is 0 capacity!!!!
}

注意:我向 Oracle 打开了一个新的 bug 以查看文档。

这是文档中的一个错误。他们忘记更新评论了。

JDK 7 :

 public ArrayList() {
     this(10);
 }

JDK 8 :

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

从 1.7 他们说在向其中添加第一个元素后将创建一个默认大小为 10 的 ArrayList ..这意味着在我们向其中添加一个元素之前不会创建 ArrayList 对象,请阅读给出的描述在 'elementData' 变量上(任何具有 elementData == EMPTY_ELEMENTDATA 的空 ArrayList 将在添加第一个元素时展开 DEFAULT_CAPACITY{它是一个 int 变量}。)。就像惰性实例化。

在 1.6 中,即使我们没有向 ArrayList 添加元素,它也会创建 10 个大小的空对象数组,这就像急切的实例化..

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

/**
 * Shared empty array instance used for empty instances.
 */
private static final Object[] EMPTY_ELEMENTDATA = {};


 /*
 * The array buffer into which the elements of the ArrayList are stored.
 * The capacity of the ArrayList is the length of this array buffer. Any
 * empty ArrayList with elementData == EMPTY_ELEMENTDATA will be expanded    
 * DEFAULT_CAPACITY when the first element is added.
 */

private transient Object[] elementData;
 /**
 * Constructs an empty list with an initial capacity of ten. (they might have forgot to update this..)
 */
public ArrayList() {
    super();
    this.elementData = EMPTY_ELEMENTDATA;
}
 /*