Increase Instance Capacity by Ten Percent

Increase Instance Capacity by Ten Percent

ArrayList doesn’t need any introduction to Java programmers. It is probably the most used component of the Java collection framework.

One of the ArrayList constructors takes Collection as an argument. This constructer is supposed to create a new ArrayList a copy of the given collection. However, if you add an additional object or a new instance, it may not necessarily expand the internal data structure. Why?

Because when an ArrayList object is constructed using an existing collection object, it will create an ArrayList instance with ten percent more capacity then the original collection (limited by maximum integer value). This increase will not be reported by the size() API. This undocumented increase provides higher performance by avoiding memory reallocation in case a few more objects were added to this instance.

Knowing this undocumented feature can save some time for performance-sensitive application programmers?especially when ArrayList doesn’t provide a constructor with a collection object and initialCapacity value.


Share the Post: