Size of an Arraylist

Asked

Viewed 1,267 times

4

In Java...

  • What is the initial size of a ArrayList?
  • Reaching the maximum size, when it "expands", its size is doubled?

2 answers

9


The initial capacity is 10 elements, if not specified in its creation. And when it reaches its 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 don’t count on it, a different version of the library can do differently.

Doubling capacity instead of allocating only the need is done to minimize a problem similar to Shlemiel the Painter's algorithm where a new small addition to ArrayList would already produce a new relocation, making the operation slower and slower. The algorithm exchanges an exaggerated amount of relocations for a possible waste of memory.

There’s something talking about it in the O.R. here and here. To official documentation says the initial capacity is 10, so this probably won’t change, documented, becomes a contract :)

-2

If the Arraylist has 10 positions allocated, when adding a new element it increases 50% its value; already the Linkedlist, increase by 100%.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.