Sobes.tech
Senior

How does HashMap expand when it fills up?

sobes.tech AI

Answer from AI

In Java, HashMap expands when the number of elements exceeds a certain threshold, usually the load factor (default 0.75) multiplied by the current array size (capacity). When this threshold is reached, a new array with an increased size (usually double) is created, and all existing entries are redistributed (rehash) into the new array.

It roughly looks like this:

  • Initially, capacity = 16
  • Load factor = 0.75
  • Maximum number of elements before expansion = 16 * 0.75 = 12
  • When adding the 13th element, expansion occurs

This helps maintain the efficiency of insert and search operations by reducing the number of collisions.

How does HashMap expand when it fills up? — Java - sobes.tech