Horrendous performance & large heap footprint of Java 8 constructor reference?

In the first case (ArrayList::new) you are using the constructor which takes an initial capacity argument, in the second case you are not. A large initial capacity (index in your code) causes a large Object[] to be allocated, resulting in your OutOfMemoryErrors.

Here are the two constructors’ current implementations:

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

Something similar happens in HashSet, except the array is not allocated until add is called.

Leave a Comment