Can you explain the internal structure of HashMap implementation?
sobes.tech AI
Answer from AI
HashMap in Java is implemented based on an array of buckets, where each bucket contains a linked list or a tree (starting from Java 8) of elements with the same hash code (collisions). Keys are hashed to determine the bucket index. When adding an element, HashMap computes the hash of the key, finds the bucket, and checks if an element with the same key already exists — if so, it updates the value; otherwise, it adds a new node.
From Java 8, if a bucket contains too many elements (more than 8), the linked list is converted into a balanced tree (TreeNode) to speed up search.
Main components:
- Array Node<K,V>[] table — the buckets.
- Node<K,V> — an element with fields key, value, hash, and a reference to the next element.
When the number of elements increases (default load factor of 0.75), the array is expanded and elements are redistributed (rehash).
An example of a simplified node structure:
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Node<K,V> next;
// constructor and methods
}