Sobes.tech
Junior — Middle

How does the number of buckets in a HashMap grow when adding elements?

sobes.tech AI

Answer from AI

In Java, the HashMap's number of buckets increases when elements are added and the number exceeds the threshold, which is equal to capacity * load factor (default load factor = 0.75). When this threshold is reached, a resize operation occurs, during which the size of the bucket array doubles, and all existing elements are redistributed across the new buckets considering the new size.

For example: if the initial capacity is 16, then adding 12 elements (16 * 0.75) will trigger an expansion to 32 buckets.

This helps maintain efficient access and insertion times by reducing the number of collisions.