Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

JDK doc for ArrayList constructor says that the initial capacity is 10.

This is actually wrong as the initial capacity is 0 till something is added to the list. I checked the source of Open JDK as well as the src.zip that comes with JDK.

I understand that this is a performance optimization but would this be considered a bug?

like image 561
Aseem Bansal Avatar asked Nov 13 '15 08:11

Aseem Bansal


2 Answers

Valid only for JDK up to 6

It is not an error.

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

It not means that the size of the list is 10. Only that an empty array of size 10 is created.

When an object is added to the list an internal pointer to the last element is moved one over. If the capacity of the array is not sufficient another array is created with an higher capacity and the old array is copied in the first part of the new array. In this moment the capacity of the array is not more 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 JDK (from java 1.7)

Important NOTE: Yes in the newer versions of ArrayList (I think from Java7) the source code has changed. The documentation remains the old one. So yes it is a bug on the documentation!

Here the new version of constructor

private static final Object[] EMPTY_ELEMENTDATA = {};

....

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

NOTE: I opened a new bug to Oracle to review the documentation.

like image 109
Davide Lorenzo MARINO Avatar answered Nov 11 '22 23:11

Davide Lorenzo MARINO


It's a mistake in the documentation. They forgot to update the comment.

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;
}
like image 39
TheLostMind Avatar answered Nov 11 '22 23:11

TheLostMind