Middle
Tell me about the structure of HashMap.
sobes.tech AI
Answer from AI
HashMap in Java is a data structure that implements an associative array (dictionary), where keys are mapped to values using a hash function.
Main components of HashMap:
- Bucket array: each element of the array contains a linked list (or a tree in newer versions) of elements with the same hash.
- Hash function: computes the bucket index based on the key.
- Collision handling: when hash codes collide, elements are stored in a linked list or a tree within the bucket.
When inserting an element:
- The hash of the key is computed.
- The bucket index is determined (usually
hash % capacity). - If the bucket is empty, the element is placed there.
- If the bucket is occupied, the list/tree is traversed to find the key or add a new element.
Searching is similar: compute the index, then iterate through the elements in the bucket to find the desired key.
Example of simple usage:
Map<String, Integer> map = new HashMap<>();
map.put("apple", 3);
map.put("banana", 5);
int count = map.get("apple"); // 3
HashMap provides amortized constant time access O(1), but performance may degrade with a high number of collisions.