Size of an ArrayList

3

In Java ...

  • What is the initial size of a ArrayList ?
  • Attaining the maximum size, when it "expands", is its size doubled?
asked by anonymous 13.03.2015 / 20:12

1 answer

5

The initial capacity is 10 elements, if not specified at creation. And when it reaches the maximum it is transparently reallocated (internal implementation) with twice the current capacity if the new capacity is sufficient. But note that this is implementation detail, so do not count on this, a different version of the library might do differently.

Duplicating capacity rather than just allocating the need is done to minimize a problem similar to that of Shlemiel the Painter's algorithm where a new small addition to ArrayList would already produce a new reallocation, making the operation slower and slower. The algorithm exchanges an exaggerated amount of reallocations for a possible memory leak.

There's something about this in SO here and here . The official documentation says that the initial capacity is 10 , then this probably will not change.

    
13.03.2015 / 20:18