Junior — Middle
What happens inside a HashMap when a new key-value pair is inserted?
sobes.tech AI
Answer from AI
When a new key-value pair is inserted into a HashMap, the following occurs:
- The hash code of the key is computed using the
hashCode()method. - The hash code is transformed into an array index (the backend of HashMap is an array of buckets) using an operation such as taking the remainder modulo the array size or a bitwise mask.
- If there are no elements in the bucket at this index, a new entry with the key and value is created.
- If the bucket already contains elements (collision), the chain (linked list or tree if many elements) is traversed to check if the key already exists:
- If the key is found, the value is updated.
- If the key is not found, a new entry is added to the chain.
- When a certain load factor threshold is reached, the array is resized and elements are redistributed (rehash).
Example:
Map<String, Integer> map = new HashMap<>();
map.put("apple", 5); // hash("apple") is computed, index determined, and the entry is inserted