Junior — Middle
How is an element added to a HashMap data structure?
sobes.tech AI
Answer from AI
HashMap in Java is a data structure that stores key-value pairs and provides fast access by key.
Adding an element to a HashMap occurs as follows:
- The hash code of the key is computed using the
hashCode()method. - Based on the hash code, the index of the bucket in the array is determined.
- If the bucket is empty, a new entry with the key and value is created.
- If there are already elements in the bucket (collision), a search is performed through the chain (linked list or tree) to check if the key already exists.
- If the key is found, the value is updated.
- If not, a new element is added to the chain.
Example of adding an element:
HashMap<String, Integer> map = new HashMap<>();
map.put("apple", 5); // adds a key-value pair "apple" and 5
Calling put initiates the process described above, ensuring data storage and quick access.