Explain the principle of how HashMap works.
sobes.tech AI
Answer from AI
HashMap in Java is a data structure that implements the Map interface, storing key-value pairs and providing fast access to values by key.
The working principle is based on using a hash function to compute an index in an array of buckets. When a key-value pair is added, the hashCode() method is called on the key, and the result is transformed into an array index. If there are already elements in this bucket (collision), they are stored as a linked list or a tree (starting from Java 8, when there are many collisions, the list is converted into a balanced tree to improve performance).
When searching for a value by key, HashMap calculates the index based on the hash of the key and then iterates over the elements in the bucket, comparing keys using the equals() method. This ensures an average complexity of insert and search operations close to O(1).
Example:
Map<String, Integer> map = new HashMap<>();
map.put("apple", 5);
int value = map.get("apple"); // returns 5
It is important that keys have correctly implemented hashCode() and equals() methods to avoid errors during search and storage.