And how is the length of the array itself determined?
By default, an array of 16 items (baskets) is created.
HashMap has attributes such as:
capacity - capacity / capacity (the current size of the array is not a class field );size - the number of elements in the HashMap ;loadFactor - load factor;threshold is the threshold for the number of HashMap elements.
In this case, the threshold calculated as capacity * load factor .
After adding a pair to the HashMap , a check is performed:
if (size++ >= threshold)
and, if the number of HashMap elements is equal to or greater than the threshold value, a new array is created, the size of which is twice the size of the old array:
resize(2 * table.length);
at the same time, all elements of the old array are distributed to the new array and the capacity value is changed and the threshold recalculated.
Example:
Created a HashMap with default parameters:
capacity = 16size = 0loadFactor = 0.75threshold = (int)(16 * 0.75f) = 12
Added 11 different pairs:
capacity = 16size = 11loadFactor = 0.75threshold = 12
After adding the 12th pair we get:
capacity = 32size = 12loadFactor = 0.75threshold = (int)(32 * 0.75f) = 24
All of the above is true for JDK 7 and below, but in JDK 8 the table is expanded a little differently.