Junior — Middle
How does inserting an element into a HashMap data structure occur?
sobes.tech AI
Answer from AI
In Java, the HashMap data structure is implemented based on an array of buckets, each of which contains a linked list (or a tree if there are many elements). The insertion of an element occurs as follows:
- The hash code of the key is computed using the
hashCode()method. - The hash code is transformed into an array index (bucket) using a modulo operation or bit masking.
- It checks whether an element with the same key already exists in the bucket (comparison via
equals()). - If the key is found, the value is updated.
- If the key is not found, a new entry is created and added to the beginning of the bucket's list (or to the tree).
Example:
HashMap<String, Integer> map = new HashMap<>();
map.put("key", 1);
Inside put, the index is calculated and the key-value pair is added to the corresponding bucket.
If the number of elements exceeds the load factor threshold, a rehash occurs with an increase in the array size.