Sobes.tech
Junior — Middle

What happens inside a HashMap data structure when a new key-value pair is added?

sobes.tech AI

Answer from AI

When a new key-value pair is added to a HashMap, several steps occur:

  1. The hash code of the key is computed using the hashCode() method.
  2. The hash code is transformed into an array index (back-end of HashMap) using bitwise operations.
  3. The array cell (bucket) is checked for an existing element with the same key:
    • If none exists, a new Node is created and added to the bucket.
    • If one exists, the keys are compared using equals():
      • If the keys match, the value is updated.
      • If the keys differ (collision), the new entry is added to a linked list or tree (in newer Java versions, a red-black tree is used for optimization when collisions are high).
  4. When a certain load factor threshold is reached, the array is resized and elements are redistributed.

Thus, HashMap provides fast access and data updating through hashing and efficient collision resolution.