Junior — Middle
How is the initial size of the internal array in HashMap data structures chosen?
sobes.tech AI
Answer from AI
In the implementation of HashMap in Java (and Android), the initial size of the internal array (capacity) is by default 16. This means that when creating a HashMap without specifying a size, an array of 16 buckets is created to store the elements.
The size is always chosen as a power of two to optimize index calculation for the key using bitwise operations. When adding elements, if the number of filled buckets exceeds the threshold (load factor, default 0.75), the array size is doubled.
Example of creating a HashMap with an initial size:
Map<String, Integer> map = new HashMap<>(32); // internal array will be of size 32
If the size is not specified, the default value of 16 is used.