The Java – JDK API documentation is incorrect for the ArrayList constructor Is this a bug?

The JDK DOC of ArrayList constructor indicates that the initial capacity is 10

This is actually wrong because the initial capacity is 0 until it is added to the list I checked the source code of the open source JDK and the src.exe provided with the JDK zip.

I understand that this is a performance optimization, but will it be considered a mistake?

Solution

For JDK only, up to 6

This is not a mistake

The initial capacity of the internal array used to store list elements is really 10

This does not mean that the size of the list is 10 Only an empty array of size 10 is created

When an object is added to the list, an internal pointer to the last element moves to a If the array does not have enough capacity, another array with higher capacity is created and the old array is copied to the first part of the new array At this moment, the capacity of the array will not exceed 10

The code is:

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];
}

For newer jdks (from Java 1.7)

Note: the source code of the updated ArrayList (I think from Java 7) has changed The file is still old So yes, this is an error in the document!

Here is the new version of the constructor

private static final Object[] EMPTY_ELEMENTDATA = {};

....

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

Note: I opened a new error to Oracle to view the document

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>