Java Collections – Default Capacity Differences

collectionsjava

Looking at different collection constructors the question comes to mind. Why does ArrayList()
construct an empty list with an initial capacity of ten and ArrayDeque()
constructs an empty array deque with an initial capacity sufficient to hold 16 elements.

Best Answer

Short answer

Because ArrayDeque capacity must be a power of two, and 16 is the smallest power of two that is at least 10.


ArrayDeque needs to use a lot of % operations everywhere to wrap around a linear array that pretends to be circular.

a % b can be expressed as a & (b - 1) if b is a power of two. The bitwise AND is massively faster so the capacity of ArrayDeque is restricted to be power of two. All % operations are performed with bitmasking instead of actual % in the implementation.

This is also why the newer HashMap doesn't use prime number table sizes but power of two, again because the % operation needs to be performed so often and the bitwise and is that much faster.

So if the baseline is 10, then structures that have power of two limitations should use 16 becase it's the smallest power of two that is at least 10.

Related Topic