Understanding Java HashMap: Principles, Operations, and Interview Insights
This article explains the fundamentals of Java's HashMap, covering its internal structure, hash computation, insertion and retrieval processes, collision handling, resizing, thread‑safety concerns, differences with Hashtable, and practical interview questions with code examples.
The piece begins with a light‑hearted dialogue between two students discussing Java interview topics, then dives into detailed explanations of HashMap concepts useful for interview preparation.
Why use HashMap? It stores key‑value pairs in an array of buckets, combines array and linked‑list structures for fast lookups, is unsynchronized for speed, and permits null keys and values.
How HashMap works – HashMap relies on hashing: put(key, value) computes the key's hashCode(), applies a perturbation function, and determines the bucket index. get(key) uses the same hash to locate the bucket and then compares keys with equals().
The article provides a simplified initialization example:
Node[] table = new Node[16]; // bucket array
class Node {
int hash; // hash value
Object key; // key
Object value; // value
Node next; // next node for chaining
}Insertion ( put) steps:
Compute the key's hash and bucket index.
If the bucket is empty, store the node.
If a collision occurs, link the new node to the existing chain.
If the chain length exceeds 8, convert it to a red‑black tree; if it falls below 6, revert to a list.
Replace the value if the key already exists.
If the load factor (default 0.75) is exceeded, resize the table (double its size) and rehash entries.
Retrieval ( get) steps:
Compute the hash and locate the bucket.
Traverse the chain (or tree) comparing keys with equals() to find the matching entry.
Collision reduction techniques include using a good hash function (perturbation of high and low bits), choosing immutable key types with proper equals() and hashCode() implementations (e.g., String, Integer), and applying a supplemental hash function.
The article also discusses why HashMap switches from linked lists to red‑black trees when buckets become deep, and why it does not always use trees (overhead for small lists).
When the map exceeds its load factor, it resizes (rehashing) which can cause race conditions in multithreaded environments, potentially leading to infinite loops; therefore, HashMap is not thread‑safe.
Differences between HashMap and Hashtable are highlighted: default capacities, synchronization (Hashtable is synchronized and slower), and performance implications.
Concurrent alternatives are presented: ConcurrentHashMap (JDK 1.7) uses segmented locks (Segment) to allow higher concurrency.
In JDK 1.8, ConcurrentHashMap replaces segments with CAS and synchronized blocks, employing volatile fields for visibility and supporting treeification for large bins.
Code examples illustrate the internal hash function and a sample ConcurrentHashMap usage that can dead‑lock in JDK 1.8 but is fixed in later versions:
public class ConcurrentHashMapDemo {
private Map<Integer,Integer> cache = new ConcurrentHashMap<>(15);
public static void main(String[] args) {
ConcurrentHashMapDemo ch = new ConcurrentHashMapDemo();
System.out.println(ch.fibonaacci(80));
}
public int fibonaacci(Integer i) {
if(i==0||i==1) {
return i;
}
return cache.computeIfAbsent(i, key -> {
System.out.println("fibonaacci : "+key);
return fibonaacci(key-1)+fibonaacci(key-2);
});
}
}Overall, the article provides a comprehensive overview of HashMap internals, practical interview questions, and concurrency considerations for Java developers.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java Captain
Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
