Sobes.tech
Junior — Middle

Millised protsessid toimuvad HashMapi sees, kui sinna lisatakse uus element?

sobes.tech AI

Vastus AI-lt

When a new element is added to a HashMap, several key steps occur:

  1. The hash code of the key is calculated 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, a 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 the put method, the described process is executed to correctly place the key-value pair.