Middle
How does HashMap work?
sobes.tech AI
Answer from AI
HashMap stores data as key-value pairs. Internally, it uses an array of Nodes (or entries).
When adding a pair:
- The hash code of the key is computed using
hashCode(). - The index in the array (bucket) is determined by the hash code.
- If the bucket already contains elements, the key's uniqueness is checked using
equals(). - If the key is unique, the pair is added to the bucket. In case of collisions (different keys with the same hash), a linked list or a balanced tree (red-black tree) is used to store elements in the same bucket.
// Example of a HashMap node
class Node<K,V> implements Map.Entry<K,V> {
final int hash; // hash of the key
final K key; // key
V value; // value
Node<K,V> next; // reference to the next element in the bucket in case of collision
Node(int hash, K key, V value, Node<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
// ... other methods like getKey(), getValue(), setValue()
}
When retrieving a value by key:
- The hash code of the key is computed.
- The index in the array is determined.
- The search for the key in the corresponding bucket is performed using
equals().
Important points: Concurrency: HashMap is not thread-safe.
null: Allows storing one null key and multiple null values.
Performance: On average, put and get operations work in O(1), but with high collisions, they can degrade to O(n) when using a linked list.
Load Factor: When a certain fill percentage is reached, the array is resized (rehashing), which can be resource-intensive.
| Method | Average Complexity | Worst-case Complexity |
|---|---|---|
| put(key, value) | O(1) | O(n) |
| get(key) | O(1) | O(n) |
| containsKey(key) | O(1) | O(n) |