Fundamentals 14 min read

Deep Dive into Java HashMap: Implementation, hashCode/equals, Collision Handling, and Interview Questions

This article provides a comprehensive overview of Java's HashMap, covering its place in the Set and Map families, internal implementation details, the relationship between hashCode() and equals(), collision resolution strategies, basic operations, differences from Hashtable, and several classic interview problems such as Top‑K frequency and LRU cache design.

Sohu Tech Products
Sohu Tech Products
Sohu Tech Products
Deep Dive into Java HashMap: Implementation, hashCode/equals, Collision Handling, and Interview Questions

HashMap is one of the most frequently encountered data structures in both daily development and technical interviews. It is often used to solve problems like LeetCode's Two Sum variations and the classic LRU Cache.

The article first introduces the Set family (HashSet, LinkedHashSet, TreeSet) and then the Map family (HashMap, LinkedHashMap, TreeMap), highlighting their characteristics and typical time complexities.

HashMap Implementation : each key is processed by a hash function to produce a hash value, which determines the bucket index in an internal array. When multiple keys map to the same bucket, a hash collision occurs.

Collision handling in Java uses Separate chaining : earlier JDK versions store colliding entries in a linked list, while JDK 8 switches to a red‑black tree when a bucket's chain exceeds eight nodes, improving lookup performance.

The article explains the crucial role of hashCode() and equals() . hashCode() determines the bucket, while equals() resolves whether two objects are truly equal. Overriding both methods is mandatory to maintain the contract that equal objects must have identical hash codes.

Sample code showing the default equals() implementation (reference equality) and a custom comparison using == is presented, followed by an example of overriding equals() in String to compare content rather than references.

public V put(K key, V value) {
    int index = getIndex(key);
    Node
node = array[index];
    Node
head = node;
    while (node != null) {
        // key already exists, update value
        if (checkEquals(key, node)) {
            V prev = node.value;
            node.value = value;
            return prev;
        }
        node = node.next;
    }
    // key does not exist, insert new node at head
    Node
newNode = new Node(key, value);
    newNode.next = head;
    array[index] = newNode;
    return null;
}

The article also compares HashMap with Hashtable, noting that Hashtable is synchronized (thread‑safe) while HashMap is not, and that HashMap permits null keys whereas Hashtable does not.

Two classic interview problems are discussed:

Top‑K Frequent Words : use a HashMap<String, Integer> to count frequencies and a min‑heap of size k to extract the most frequent words.

LRU Cache : mentioned as a high‑frequency interview topic, with a note that a full implementation is omitted.

class Solution {
    public List
topKFrequent(String[] words, int k) {
        // Step 1: count frequencies
        Map
map = new HashMap<>();
        for (String word : words) {
            int count = map.getOrDefault(word, 0);
            map.put(word, ++count);
        }
        // Step 2: min‑heap to keep top k
        PriorityQueue
> minHeap =
            new PriorityQueue<>(k + 1, (e1, e2) -> {
                if (e1.getValue().equals(e2.getValue()))
                    return e2.getKey().compareTo(e1.getKey());
                return e1.getValue().compareTo(e2.getValue());
            });
        // Step 3: populate heap
        for (Map.Entry
entry : map.entrySet()) {
            minHeap.offer(entry);
            if (minHeap.size() > k) minHeap.poll();
        }
        List
res = new ArrayList<>();
        while (!minHeap.isEmpty()) res.add(minHeap.poll().getKey());
        Collections.reverse(res);
        return res;
    }
}

Overall, the article serves as a thorough guide for understanding HashMap internals, mastering hashCode() and equals() , handling collisions, and preparing for related interview questions.

JavaInterviewHashMapData StructurescollisionequalsHashCode
Sohu Tech Products
Written by

Sohu Tech Products

A knowledge-sharing platform for Sohu's technology products. As a leading Chinese internet brand with media, video, search, and gaming services and over 700 million users, Sohu continuously drives tech innovation and practice. We’ll share practical insights and tech news here.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.