Junior — Middle
How does the number of buckets in a HashMap structure change when adding elements?
sobes.tech AI
Answer from AI
In Java, the number of buckets (internal containers for storing elements) in HashMap is initially fixed (usually 16). When adding elements, if the number of elements exceeds the load factor threshold (default 0.75), the number of buckets is increased — HashMap expands by doubling (multiplied by 2). This is done to reduce the number of collisions and maintain the performance of insert and search operations.
Example: if initially there are 16 buckets, and the number of elements exceeds 12 (16 * 0.75), the size of HashMap will increase to 32 buckets, and all elements will be redistributed across the new buckets.