HashMap handles collisions using a technique called chaining. When two keys have the same hash code, they are stored in the same bucket. Instead of overwriting one value, the HashMap stores the entries in a linked list (or a balanced tree if the list becomes too long).

  • Chaining: Multiple key-value pairs that hash to the same bucket are stored as a list or tree.
  • Load factor: When the number of entries exceeds a threshold, the HashMap resizes itself to reduce collisions.

This ensures that HashMap can still offer efficient lookups, even when collisions occur.