Why is the new ability arraylist (oldCapacity * 3) / 2 + 1?
The main reason is the (asymptotic) difficulty of adding a sequence of items to a list.
Note that the method add
is called internally ensureCapacity(size+1)
. When the size of the internal array grows, all elements must be copied to the new larger array.
If the size was only increased by a constant amount (which will be 1 for each call add
), then adding n elements will have complexity O (n 2 ) .
Instead, the size is always increased by a constant factor. Then adding n elements only has O (n) complexity .
source to share
Resizing an array is relatively expensive. He wants to try and make sure that if the method is invoked using the ensureCapacity(11)
, ensureCapacity(12)
, ensureCapacity(13)
, ... it does not change the size of the array each time. Thus, it changes to a reasonable chunk (50% increase) instead of the specified minimum.
source to share