Sobes.tech
Junior — Middle

What happens inside HashMap when a new element is added?

sobes.tech AI

Answer from AI

When a new element is added to a HashMap, several key 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 (bucket) using an operation that considers the array size.
  3. If the bucket is empty, the element is placed directly there.
  4. If the bucket already contains elements (collision), the linked list or tree (in newer Java versions) in that bucket is traversed:
    • If the key already exists, the value is updated.
    • If the key does not exist, the new element is added to the end of the list or to the tree.
  5. When a certain load factor threshold is reached, the array is resized (rehash) to maintain performance.

Example of adding:

HashMap<String, Integer> map = new HashMap<>();
map.put("key", 1);

Inside put, the described process occurs for correct placement of the key-value pair.