Junior — Middle
How does the insertion of new elements into a HashMap data structure occur?
sobes.tech AI
Answer from AI
In HashMap, inserting a new element occurs as follows:
- The hash code of the key is computed and used to determine the index of the bucket in the array.
- If the bucket is empty, a new entry with the key and value is created.
- If the bucket already contains elements (collision), a traversal of the linked list or tree (in newer Java versions) is performed to check for the presence of the key:
- If the key is found, the value is updated.
- If the key is not found, the new element is added to the end of the list or to the tree.
Example in Java:
HashMap<String, Integer> map = new HashMap<>();
map.put("key1", 100); // hash is computed, bucket is determined, element is inserted
Thus, HashMap provides fast insertion and lookup through hashing and efficient collision resolution.