Why does ensureCapacity() in Java ArrayList extend the capacity with a const 1.5 or (oldCapacity * 3)/2 + 1?
Resizing the array is a relatively expensive operation. It wants to try and make sure that if the method gets called with ensureCapacity(11), ensureCapacity(12), ensureCapacity(13), ... it should not have to resize the array every time. So it resizes by a reasonable chunk (increase by 50%) instead of the minimum specified.
The main reason lies the (asymptotic) complexity of adding a sequence of elements to the list.
Note that the add method internally calls ensureCapacity(size+1). When the size of the internal array is increased, all elements have to be copied into the new, larger array.
If the size was only increased by a constant amount (which would be 1 for each call to add), then adding n elements would have a complexity of O(n2).
Instead, the size is always increased by a constant factor. Then, adding n elements only has a complexity of O(n).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With