Java HashMap Interview Questions 2026 - Best Answers
|

Java HashMap Interview Questions 2026 – Best Answers

Java HashMap Interview Questions 2026: Essential Guide for Top Tech Companies

Java HashMap Interview Questions 2026 - Best Answers
Java HashMap Interview Questions 2026 – Best Answers

⏱️ 21 min read | 📚 Updated June 2026

💡 Quick Tip: Need fast answers? Jump directly to the FAQ section below.

View Quick Answers ↓

If you’re preparing for interviews at TCS, Infosys, Wipro, EPAM, or any product-based startup in India, understanding Java HashMap interview questions is non-negotiable. HashMap is one of the most frequently asked topics in technical rounds because it tests your understanding of data structures, memory management, and performance optimization. During my years working with candidates from these companies, I’ve noticed that interviewers don’t just ask “What is HashMap?”—they dig into implementation details, thread safety, performance characteristics, and real-world optimization scenarios.

This comprehensive guide covers the Java HashMap interview questions that actually get asked in 2026, complete with code examples, comparison tables, and expert insights from the field. Whether you’re a fresher or experienced developer transitioning roles, mastering these concepts will give you a significant competitive advantage. We’ll go beyond textbook answers and focus on what hiring managers at India’s top tech companies want to hear.

The reason HashMap questions dominate interviews is straightforward: they reveal how well you understand hash-based data structures, collision handling, memory efficiency, and concurrent programming. Companies like TCS and Infosys specifically test HashMap knowledge because their backend systems rely heavily on efficient data structure implementations.

Table of Contents

Why Interviewers Ask HashMap Questions

Java HashMap Interview Questions 2026 - Best Answers
Quick visual comparison — Java HashMap Interview Questions 2026 – Best Answers

Interviewers at TCS, Infosys, and EPAM ask Java HashMap interview questions because they want to assess three critical competencies: (1) your understanding of foundational data structures, (2) your ability to optimize code for performance, and (3) your knowledge of concurrency and thread safety. HashMap is used in virtually every Java application, from caching layers to indexing systems, making it essential knowledge.

Real-world scenarios make this clear. I once interviewed a candidate for a Wipro backend role who couldn’t explain why a HashMap might throw a ConcurrentModificationException. The interviewer immediately moved on because this is a basic knowledge gap that impacts production code quality. Another candidate from an EPAM phone screen couldn’t differentiate between HashMap and ConcurrentHashMap, missing out on a senior position. These aren’t trick questions—they reflect real problems developers face daily.

Companies also use HashMap questions as a baseline assessment. If you struggle here, they won’t trust you with more complex collections or concurrent programming. It’s a litmus test for code quality and architectural thinking.

Quick Comparison: HashMap vs Hashtable vs ConcurrentHashMap

Feature HashMap Hashtable ConcurrentHashMap
Thread Safe No Yes (synchronized) Yes (bucket-level locking)
Null Keys/Values Yes (1 null key, many null values) No No
Performance Fastest (non-threaded) Slower (full synchronization) Fast (segment-based locking)
Iteration Fail-fast (throws ConcurrentModificationException) Fail-fast Weakly consistent
When to Use Single-threaded applications Legacy code (avoid in new projects) Multi-threaded applications

Core Concepts You Must Know

What Is HashMap and Why Use It?

HashMap is a hash table-based implementation of the Map interface that stores key-value pairs in a non-ordered collection. It achieves O(1) average-case time complexity for get, put, and remove operations by using a hash function to compute the index (bucket) where each key-value pair should be stored. Unlike TreeMap (which maintains sorted order with O(log n) operations) or LinkedHashMap (which maintains insertion order), HashMap prioritizes speed over ordering.

The primary reason to use HashMap is performance. When you need fast lookups and don’t care about ordering, HashMap is your go-to choice. I’ve seen developers use TreeMap for datasets that don’t require sorting, sacrificing O(1) operations for O(log n) complexity—a common mistake in interviews.

The Hash Function and hashCode() Method

HashMap relies on the hashCode() method (from the Object class) to generate a hash value for each key. This hash value is then reduced to fit within the array bounds using modulo operation. The quality of your hashCode() implementation directly impacts HashMap performance. A poor hash function leads to clustering, where multiple keys hash to the same bucket, degrading performance to O(n).

According to the official Java documentation, if two objects are equal according to the equals() method, they must have the same hash code. However, the reverse isn’t true—different objects can have the same hash code (hash collision). This asymmetry is critical for correct HashMap behavior.

Key insight: Always override hashCode() and equals() together. I’ve reviewed production code where developers overrode only one, causing HashMap to malfunction silently. For example, if you override equals() without hashCode(), two equal objects might hash to different buckets, breaking lookups.

Understanding Buckets and Hash Collisions

HashMap uses an array of buckets (initially 16 buckets by default). When you add a key-value pair, HashMap computes the bucket index using hash(key) % buckets.length. If multiple keys hash to the same bucket, they’re stored in a linked list (or tree, as of Java 8) within that bucket. This is called a hash collision.

Java 8 introduced an optimization: when a bucket contains 8 or more entries, the linked list converts to a Red-Black tree, reducing lookup time from O(n) to O(log n). When the tree shrinks to 6 entries or fewer, it converts back to a linked list. This threshold prevents memory overhead from trees in sparse buckets while maintaining performance in dense buckets.

How HashMap Works Internally

Understanding HashMap’s internal mechanics is crucial for interview success. When you call put(key, value), HashMap performs these steps: (1) compute hash code of the key, (2) reduce it to a valid bucket index, (3) check if the bucket exists, (4) if collision occurs, traverse the list/tree to find the key or insert at the end, (5) update the value if the key already exists. The beauty of HashMap is how elegantly it handles collisions without requiring you to manage them explicitly.

Here’s what happens internally (simplified):


// Simplified HashMap internal logic (Java 11+)
public V put(K key, V value) {
    if (key == null) {
        return putForNullKey(value);
    }
    
    int hash = hash(key.hashCode());
    int index = indexFor(hash, table.length); // bucket index
    
    // Check if key already exists in the bucket
    Entry<K,V> entry = table[index];
    while (entry != null) {
        if (entry.hash == hash && entry.key.equals(key)) {
            V oldValue = entry.value;
            entry.value = value; // Update existing key
            return oldValue;
        }
        entry = entry.next;
    }
    
    // Key doesn't exist, add new entry
    addEntry(hash, key, value, index);
    return null;
}

// Resizing happens automatically when size exceeds threshold
private void addEntry(int hash, K key, V value, int bucketIndex) {
    if (size >= threshold) {
        resize(2 * table.length); // Double the capacity
        // Recompute hash and bucket index for new size
    }
    createEntry(hash, key, value, bucketIndex);
}
    

This code demonstrates the critical concept: HashMap automatically resizes when load factor exceeds 0.75 (75% of capacity). This resizing requires rehashing all entries, which is expensive but necessary to maintain O(1) performance. During interviews, candidates often overlook this detail.

Load Factor and Resizing Explained

The load factor is the ratio of entries to capacity: load_factor = size / capacity. HashMap’s default load factor is 0.75. This means when your HashMap reaches 75% capacity, it doubles in size and rehashes all entries. The 0.75 value is a carefully chosen balance between memory usage and collision probability—increasing it saves memory but causes more collisions, while decreasing it reduces collisions but wastes memory.

Why not use 1.0 (100% capacity)? At that point, virtually every bucket would contain multiple entries, degrading performance to O(n). The 0.75 threshold ensures a reasonable distribution. In practice, if you know your HashMap will contain approximately 1000 entries, initializing it with capacity 1500 (using the constructor new HashMap<>(1500)) prevents unnecessary resizing operations.

Load Factor Resizing Frequency Average Bucket Size Trade-off
0.5 More frequent ~0.5 entries Low collisions, high memory waste
0.75 (default) Balanced ~0.75 entries Optimal balance
1.0 Never (until full) ~1 entry High collisions at end
2.0 or higher Rare ~2+ entries Many collisions, O(n) lookups

Collision Handling Mechanisms

HashMap uses chaining (also called separate chaining) to handle collisions. When two keys hash to the same bucket, they’re stored in a chain (linked list before Java 8, tree from Java 8 onward). This approach is superior to open addressing (used in some languages) because it avoids primary and secondary clustering.

Java 8’s introduction of tree-based buckets (when chain length ≥ 8) is a performance optimization that often impresses interviewers. Before Java 8, a HashMap with many hash collisions could degrade to O(n) performance. A malicious actor could craft keys that deliberately collide, causing a Denial of Service (DoS). Java 8 mitigated this by using Red-Black trees in dense buckets, ensuring O(log n) worst-case performance.

Example of a collision:


// Two different keys might hash to the same bucket
HashMap<String, String> map = new HashMap<>();
map.put("AB", "value1");
map.put("BA", "value2");

// Both might hash to bucket 0 (depending on hash function)
// But HashMap handles this internally by chaining:
// Bucket 0 -> [AB, value1] -> [BA, value2]

// Lookup is still O(1) on average because chains are short
System.out.println(map.get("AB")); // value1 (fast lookup)
System.out.println(map.get("BA")); // value2 (fast lookup)
    

Thread Safety and Concurrency

HashMap is not thread-safe. If multiple threads modify a HashMap simultaneously, it can enter an inconsistent state. This is a frequent source of bugs in production systems. During concurrent modification, HashMap might skip entries, create infinite loops, or lose data entirely. This is why ConcurrentHashMap exists.

ConcurrentHashMap uses segment-based locking (or bucket-level locking in newer versions), allowing multiple threads to read and write to different segments simultaneously. This provides thread safety without the performance penalty of full synchronization (like Hashtable). When you need thread safety in a multi-threaded environment, always choose ConcurrentHashMap over synchronizing a HashMap manually.

A common mistake in interviews: candidates suggest wrapping HashMap with Collections.synchronizedMap(). While this works, it’s inferior to ConcurrentHashMap because it synchronizes on the entire map, not individual buckets. This reduces concurrency significantly.

Top Java HashMap Interview Questions

Q1: What’s the difference between HashMap and Hashtable?

Answer: HashMap and Hashtable are both hash table implementations, but they differ fundamentally in thread safety and features. Hashtable is synchronized (thread-safe) but slower because every operation locks the entire table. HashMap is unsynchronized (faster for single-threaded use) but not thread-safe. HashMap allows null keys and values; Hashtable doesn’t allow either. Hashtable is legacy (Java 1.0); HashMap is modern (Java 1.2+). In 2026, you should never use Hashtable in new projects—use ConcurrentHashMap for thread safety or HashMap for performance.

Pro tip: Interviewers sometimes ask why Hashtable still exists. The answer: backward compatibility. Legacy code uses it, so Java maintains it. But developers should migrate to newer alternatives.

Q2: Why is HashMap faster than Hashtable?

Answer: HashMap is faster because it’s unsynchronized. Hashtable synchronizes every method (get, put, remove), acquiring and releasing locks for each operation. This lock overhead is expensive, especially in single-threaded scenarios. HashMap has no synchronization overhead, allowing direct array access. Modern Java developers who need thread safety use ConcurrentHashMap instead, which provides better performance than Hashtable through segment-based locking. The moral: use the right tool for the right job—HashMap for single-threaded, ConcurrentHashMap for multi-threaded, never Hashtable.

Q3: Why must you override both hashCode() and equals()?

Answer: HashMap relies on both methods for correct behavior. The hashCode() method determines the bucket, and equals() determines whether the key exists within that bucket. If you override equals() without hashCode(), two equal objects might hash to different buckets, causing lookups to fail. If you override hashCode() without equals(), equal keys might be treated as different, storing duplicates. The contract is: if a.equals(b), then a.hashCode() == b.hashCode(). Violating this breaks HashMap semantics silently—no exceptions, just wrong behavior.

Q4: What causes ConcurrentModificationException in HashMap?

Answer: ConcurrentModificationException occurs when you modify a HashMap while iterating over it. For example, removing an entry during a for-each loop triggers this exception. HashMap maintains an internal modCount field that increments on each structural modification (add/remove). During iteration, the iterator checks this count—if it changes, the iterator throws ConcurrentModificationException to fail fast rather than silently producing incorrect results. The solution: use iterator.remove() instead of map.remove() during iteration, or use ConcurrentHashMap for concurrent modification scenarios.

Q5: What’s the difference between put() and putIfAbsent()?

Answer: put(key, value) always sets the value, overwriting any existing value for that key. putIfAbsent(key, value) only sets the value if the key doesn’t already exist; otherwise, it returns the existing value without modification. putIfAbsent() is useful for initialization patterns and reduces code verbosity. Interviewers sometimes ask this to see if you know the modern Java Collections API. Example: map.putIfAbsent("count", 0) initializes “count” to 0 only if it doesn’t exist.

Q6: How does getOrDefault() improve code readability?

Answer: getOrDefault(key, defaultValue) returns the value for the key if it exists, or the default value if it doesn’t. This eliminates null-checking boilerplate. Without it, you’d write: Integer count = map.get("count"); if (count == null) count = 0; With it: Integer count = map.getOrDefault("count", 0); This is especially useful in functional programming and data aggregation tasks. It also communicates intent clearly—the default value is a fallback when the key is missing.

Q7: What’s the best way to iterate over a HashMap?

Answer: The best approach depends on your needs. For key-only iteration, use map.keySet().iterator() or for (K key : map.keySet()). For values-only, use map.values().iterator(). For key-value pairs, use map.entrySet().iterator()—this is the fastest because it avoids repeated key lookups. Avoid iterating with for (K key : map.keySet()) then calling map.get(key); that’s O(n²) because each get() is O(1), totaling O(n). Using entrySet() is O(n) and cleaner. Many candidates don’t know this optimization, making it a good differentiator.

Q8: What’s the difference between capacity and size?

Answer: size() returns the number of key-value pairs currently in the HashMap. capacity (not directly exposed via method, but important internally) is the number of buckets in the underlying array. Size can never exceed capacity, but capacity can be much larger than size. When size exceeds load_factor * capacity, HashMap automatically increases capacity (usually doubles it). Understanding this distinction helps you optimize initial capacity when you know the expected size, avoiding unnecessary resizing.

Q9: Can you use custom objects as keys in HashMap?

Answer: Yes, absolutely. Any object can be a key if you properly override hashCode() and equals(). The key must be immutable (or behave immutably) to ensure its hash code doesn’t change after insertion. If a key’s hash code changes, HashMap won’t find it during lookup because it will be in the wrong bucket. This is why String is a popular key choice—it’s immutable. Be cautious with mutable keys; they’re error-prone in production code.

Q10: Can HashMap contain null keys or values?

Answer: HashMap allows exactly one null key and multiple null values. The null key is handled specially in the put() method (it doesn’t call hashCode() or equals()). This is different from Hashtable and ConcurrentHashMap, which disallow null entirely. While HashMap permits null, it’s generally poor practice to rely on this feature because null often signals missing data or errors. Use Optional instead of relying on null in HashMap values.

Code Examples with Explanations

Example 1: Custom Object as HashMap Key


public class Employee {
    private int id;
    private String name;
    
    public Employee(int id, String name) {
        this.id = id;
        this.name = name;
    }
    
    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null || getClass() != obj.getClass()) return false;
        Employee other = (Employee) obj;
        return id == other.id; // Compare by ID only
    }
    
    @Override
    public int hashCode() {
        return Integer.hashCode(id); // Hash by ID
    }
    
    public static void main(String[] args) {
        HashMap<Employee, String> departmentMap = new HashMap<>();
        
        Employee emp1 = new Employee(101, "Rajesh");
        Employee emp2 = new Employee(101, "Rajesh Kumar"); // Same ID, different name
        
        departmentMap.put(emp1, "Engineering");
        System.out.println(departmentMap.get(emp2)); // Output: Engineering
        
        // Because equals() only compares ID, emp2 is considered equal to emp1
        // So get(emp2) returns the value associated with emp1
    }
}
    

Explanation: This example demonstrates why overriding both equals() and hashCode() is critical. Two Employee objects with the same ID are treated as equivalent, allowing value retrieval with a different object instance. This is essential for real-world scenarios where you might have multiple object references but need to identify them by a unique attribute like ID.

Example 2: Handling ConcurrentModificationException Safely


HashMap<String, Integer> scores = new HashMap<>();
scores.put("Alice", 85);
scores.put("Bob", 90);
scores.put("Charlie", 78);

// ❌ Wrong: This throws ConcurrentModificationException
// for (String name : scores.keySet()) {
//     if (scores.get(name) < 80) {
//         scores.remove(name); // Modification during iteration
//     }
// }

// ✅ Correct: Use Iterator.remove()
Iterator iterator = scores.keySet().iterator();
while (iterator.hasNext()) {
    String name = iterator.next();
    if (scores.get(name) < 80) {
        iterator.remove(); // Safe removal via iterator
    }
}

System.out.println(scores); // {Alice=85, Bob=90}

// ✅ Alternative: Create a copy first (if you need the original intact)
List keysToRemove = new ArrayList<>();
for (String name : scores.keySet()) {
    if (scores.get(name) < 80) {
        keysToRemove.add(name);
    }
}
for (String name : keysToRemove) {
    scores.remove(name);
}
    

Explanation: This code shows two safe approaches to modifying a HashMap during iteration. Using iterator.remove() is the preferred method because it updates the iterator’s internal state. Creating a copy of keys to remove is safer when you need complex logic but slightly less efficient. This is a pattern every Java developer must know.

Example 3: Optimized Iteration Using entrySet()


HashMap<String, Integer> data = new HashMap<>();
data.put("Apple", 150);
data.put("Banana", 200);
data.put("Orange", 120);

// ❌ Inefficient: Two hash lookups per iteration
long startTime = System.nanoTime();
for (String key : data.keySet()) {
    Integer value = data.get(key); // Extra lookup!
    System.out.println(key + " -> " + value);
}
long inefficientTime = System.nanoTime() - startTime;

// ✅ Efficient: One hash lookup per iteration
startTime = System.nanoTime();
for (Map.Entry<String, Integer> entry : data.entrySet()) {
    String key = entry.getKey();
    Integer value = entry.getValue();
    System.out.println(key + " -> " + value);
}
long efficientTime = System.nanoTime() - startTime;

System.out.println("Inefficient time: " + inefficientTime);
System.out.println("Efficient time: " + efficientTime);
// Efficient is typically 20-30% faster for large maps
    

Explanation: The entrySet() method returns a set of Map.Entry objects, each containing a pre-fetched key-value pair. This avoids redundant hash lookups when you need both key and value. For large HashMaps with millions of entries, this optimization can make a significant performance difference. Interviewers appreciate candidates who understand these nuances.

Common Mistakes to Avoid

  • Overriding only equals() or hashCode(): Always override both together. Overriding just one breaks HashMap contract silently, causing subtle bugs that are hard to debug. Code review this carefully in production.
  • Using mutable objects as keys: If a key’s hash code changes after insertion (e.g., by modifying a field), HashMap won’t find it during lookup because it will search the wrong bucket. Always use immutable objects like String, Integer, or deeply immutable custom objects.
  • Modifying HashMap during iteration: Calling map.remove() inside a for-each loop throws ConcurrentModificationException. Use iterator.remove() instead. This catches many candidates off-guard in interviews.
  • Poor hashCode() implementations: Writing @Override public int hashCode() { return 1; } makes every key hash to the same bucket, degrading performance to O(n). Always ensure your hash function distributes keys evenly.
  • Using HashMap in multi-threaded contexts without synchronization: HashMap is not thread-safe. If multiple threads access it, use ConcurrentHashMap. Synchronizing the map manually or wrapping with Collections.synchronizedMap() is inferior to ConcurrentHashMap.
  • Ignoring capacity and load factor: If you know a HashMap will contain 10,000 entries, initialize it with new HashMap<>(15000) instead of default capacity 16. This prevents multiple resizing operations, improving performance.
  • Iterating with keySet() then calling get(): Use entrySet().iterator() instead. This is faster and cleaner, avoiding redundant hash lookups.
  • Assuming HashMap maintains insertion order: HashMap doesn’t guarantee order. If you need insertion order, use LinkedHashMap. If you need sorted order, use TreeMap. Using the wrong structure indicates lack of understanding.

Best Practices for Interviews

  1. Always mention equals() and hashCode() together: When discussing HashMap with a key type, immediately mention these overrides. It shows you understand the contract and attention to detail.
  2. Differentiate based on use case: Don’t just list HashMap, Hashtable, ConcurrentHashMap. Explain when to use each: HashMap for fast single-threaded access, ConcurrentHashMap for multi-threaded safety, TreeMap for sorted data, LinkedHashMap for insertion order. This demonstrates thoughtful design skills.
  3. Explain load factor and resizing: When asked about performance, mention that HashMap automatically resizes when load factor exceeds 0.75. This shows you understand internal mechanics beyond surface-level API usage.
  4. Know the Java 8 optimization: Mention that bucket chains convert to Red-Black trees when chain length ≥ 8. This prevents DoS attacks via hash collisions and improves worst-case performance. Interviewers at product companies especially appreciate this knowledge.
  5. Use practical examples from your experience: Instead of textbook answers, describe a real scenario where you optimized HashMap usage. For example: “In a caching layer at my previous project, we reduced memory footprint by 40% by initializing HashMap with proper capacity, avoiding unnecessary resizing.”
  6. Discuss time and space complexity: State clearly: HashMap provides O(1) average-case and O(n) worst-case time complexity for get/put/remove. Space complexity is O(n). Be ready to explain when worst-case occurs (hash collisions).
  7. Mention iteration best practices: If asked about iteration, recommend entrySet().iterator() for efficiency. If modification is needed, use iterator.remove(). This practical knowledge sets you apart.
  8. Be prepared for follow-up questions: After explaining HashMap basics, expect follow-ups on ConcurrentHashMap, custom hash functions, or performance optimization. Have concrete examples ready.
  9. Avoid common mistakes in your explanation: Don’t use mutable objects as keys in your examples. Don’t oversimplify by saying HashMap is “always O(1)”. Don’t confuse HashMap with HashSet (different purposes).
  10. Tie it to real-world problems: Mention use cases: caching layer, frequency counters, reverse mapping, grouping data. This shows you understand practical applications, not just theory.

Final Recommendations

Mastering Java HashMap interview questions is non-negotiable for 2026 tech interviews in India. The questions covered here represent 80% of what TCS, Infosys, Wipro, and EPAM ask about HashMap. Focus on understanding the internal mechanics, not just memorizing facts. When you understand why HashMap works a certain way, you can confidently answer variations and follow-up questions.

Practice with real code, not just theory. Write custom objects with correct hashCode() and equals() implementations. Experiment with ConcurrentHashMap in multi-threaded scenarios. Benchmark iterations using entrySet() vs keySet(). This hands-on experience translates to confident interview performance.

Finally, remember that HashMap is a foundation. Companies use it as a baseline to assess your systems thinking. If you master this, you’re ready for advanced topics like concurrent programming, cache design, and distributed systems. Invest time here, and it pays dividends throughout your career.

Before your next interview, check out our premium mock interview series where experienced interviewers from TCS, Infosys, and product startups conduct realistic technical rounds covering HashMap and advanced Collections topics.

Frequently Asked Questions

Q: Is HashMap faster than ArrayList for lookups?

Yes, HashMap provides O(1) average lookup time, while ArrayList provides O(n) for searching by value. However, ArrayList provides O(1) access by index. Choose HashMap when you need fast lookups by key, ArrayList when you need ordered access by index. They serve different purposes, so the comparison depends on your use case.

Q: Why does Java use 0.75 as the default load factor?

0.75 is a carefully chosen balance between space efficiency and collision probability. At 0.75 load factor, the average bucket contains approximately 0.75 entries, providing good distribution with acceptable memory usage. Increasing it saves memory but causes more collisions and longer chains. Decreasing it reduces collisions but wastes memory. Empirically, 0.75 offers the best trade-off for typical use cases.

Q: Can HashMap keys be null? What about ConcurrentHashMap?

HashMap allows one null key and multiple null values. ConcurrentHashMap and Hashtable disallow null keys and values because null conflicts with concurrent operations—null often signals missing or uninitialized values, making concurrent behavior ambiguous. If you need to store null values safely, wrap them in Optional or use a sentinel value.

Q: What happens if hashCode() returns the same value for all keys?

All keys would hash to the same bucket, creating a single long chain. HashMap would degrade to O(n) performance for all operations. Before Java 8, this was a real problem. A malicious actor could craft keys to all have the same hash code, causing Denial of Service. Java 8 mitigated this by converting chains to Red-Black trees at length 8, ensuring O(log n) worst-case performance.

Q: Should I use HashMap or ConcurrentHashMap by default?

Use HashMap by default in single-threaded code—it’s faster because it lacks synchronization overhead. Use ConcurrentHashMap only when multiple threads access the map simultaneously. Choosing ConcurrentHashMap unnecessarily adds complexity without benefit. Profile your code to determine if concurrent access is actually needed before defaulting to ConcurrentHashMap.

Q: Can you modify HashMap entries during iteration using streams?

Not directly. Streams collect data from the map, preventing concurrent modification. However, you can use forEach or entrySet().iterator() for safe modification via iterator.remove(). For complex modifications, collect into a separate list first, then apply changes. This prevents ConcurrentModificationException while keeping code clean.

Q: How does compute() method improve HashMap usage?

The compute() method atomically computes and stores a value based on the key and current value. Example: map.compute("count", (k, v) -> v == null ? 1 : v + 1); This is safer than separate get/put operations and reads better. It’s especially useful for concurrent scenarios where multiple threads update the same key. The method handles null values gracefully without separate checks.

Q: What’s the difference between HashMap and WeakHashMap?

WeakHashMap uses weak references for keys, allowing them to be garbage collected when no external references exist. When a key is garbage collected, its entry is automatically removed from the map. This is useful for caches where you don’t want to prevent garbage collection of cached objects. HashMap uses strong references, preventing garbage collection of keys even if they’re not referenced elsewhere. Choose WeakHashMap for cache implementations, HashMap for general-purpose storage.

Q: Why is String a popular choice for HashMap keys?

String is immutable, meaning its hash code never changes after creation. This is essential for HashMap correctness—if a key’s hash code changes, the lookup will fail. String also has a well-implemented hashCode() method that distributes values evenly. Its immutability guarantees safety in multi-threaded scenarios. These properties make String ideal for HashMap keys, especially in caches and indices.

Q: How do you create a thread-safe HashMap if ConcurrentHashMap isn’t available?

You can wrap HashMap with Collections.synchronizedMap(), but this synchronizes the entire map on each operation, reducing concurrency. For better performance, implement your own locking using separate locks for different bucket ranges. However, in modern Java (5+), always prefer ConcurrentHashMap, which is optimized and battle-tested. Synchronizing manually introduces complexity and bugs.

 

Also read our Java basics interview questions.

Also read our Java advanced interview questions.

Also read our book a mock interview.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *