Junior — Middle
How is a new element inserted into the HashMap data structure?
sobes.tech AI
Answer from AI
Inserting a new element into a HashMap occurs as follows:
- Calculate the hash code of the key using the
hashCode()method. - Determine the bucket index in the array, using the hash code and the array size (usually through the operation
hash & (capacity - 1)). - Check for existing elements in the selected bucket:
- If the bucket is empty, create a new entry (Node) with the key and value.
- If there are already elements in the bucket, traverse the linked list or tree (in newer Java versions) to find the key.
- If the key already exists, update the value.
- If the key is not found, add a new element to the bucket.
- When a certain load factor threshold is reached, the array is resized and elements are redistributed (rehash).
Example of insertion:
HashMap<String, Integer> map = new HashMap<>();
map.put("key", 42);
Inside put, the process described above occurs for correct placement of the key-value pair.