Skip to lesson

Build a hash map with chaining

Separate chaining is a classic collision resolution technique. Each bucket stores the head of a linked list containing all colliding key-value pairs.

An array of linked lists

Chaining handles collisions by storing all entries that land in the same bucket in a small list at that bucket.

Separate chaining gives every bucket its own linked list. The array holds the first node of each chain, and each node points to the next entry in the same bucket.

Java
static class Node {    String key;    int value;    Node next;                         // next entry in the same bucket, or null    Node(String k, int v, Node n) { key = k; value = v; next = n; }}
private Node[] buckets = new Node[5];  // each slot holds the head of one chain (null at first)

The backing array stores Node references rather than raw values. Each Node holds a key, a value, and a pointer to the next node in the chain. When a collision occurs, the new entry is appended or prepended to the bucket chain. Why not overwrite colliding keys? Overwriting destroys previous data and loses stored entries. Keeping all items in one single giant list degrades search back to O(n) time.

  • Node structure: holds key, value, and next reference.
  • Buckets array: array of Node head pointers initialized to null.
  • Chain traversal: following next pointers to find matching keys.
  1. Define a Node class with key, value, and next fields.
  2. Initialize an array of Node references of chosen capacity.
  3. Hash incoming keys to determine the target bucket index.
  4. Traverse the linked list at that bucket to find or append entries.

Implementing put, get and remove

put, get and remove all start the same way: hash the key to a bucket, then walk that bucket's chain. The programs below build a small chained map.

Chaining: put keys 10, 7, 14, 6 into 4 buckets

Step 1 of 8

Array: -, -, -, -.
capacity
4
A table with 4 empty buckets, numbered 0 to 3. We will add the keys 10, 7, 14 and 6. The bucket index is key % 4.

Example 1 · Separate Chaining HashMap Implementation

ChainedMapDemo.javaJava
public class ChainedMapDemo {    static class Node {        String key;        int value;        Node next;        Node(String k, int v, Node n) { key = k; value = v; next = n; }    }
    private Node[] buckets;    private int capacity;
    public ChainedMapDemo(int cap) {        capacity = cap;        buckets = new Node[cap];    }
    private int getIndex(String key) {        return (key.hashCode() % capacity + capacity) % capacity;    }
    public void put(String key, int val) {        int idx = getIndex(key);        for (Node curr = buckets[idx]; curr != null; curr = curr.next) {            if (curr.key.equals(key)) {                curr.value = val;                return;            }        }        buckets[idx] = new Node(key, val, buckets[idx]);    }
    public Integer get(String key) {        int idx = getIndex(key);        for (Node curr = buckets[idx]; curr != null; curr = curr.next) {            if (curr.key.equals(key)) return curr.value;        }        return null;    }
    public static void main(String[] args) {        ChainedMapDemo map = new ChainedMapDemo(5);        map.put("alpha", 100);        map.put("beta", 200);        map.put("alpha", 150);        System.out.println("alpha: " + map.get("alpha"));        System.out.println("beta: " + map.get("beta"));        System.out.println("gamma: " + map.get("gamma"));    }}
Output
alpha: 150
beta: 200
gamma: null

What this code does

  • put updates existing key 'alpha' from 100 to 150.
  • Collisions prepend new nodes to the head of the bucket chain.
  • Missing key 'gamma' traverses to end of chain and returns null.

Example 2 · Removing an Entry from a Chained Map

ChainedRemoveDemo.javaJava
public class ChainedRemoveDemo {    static class Node {        String key; int val; Node next;        Node(String k, int v, Node n) { key = k; val = v; next = n; }    }
    public static void main(String[] args) {        Node head = new Node("c", 3, new Node("b", 2, new Node("a", 1, null)));        // Remove "b" from list "c" -> "b" -> "a"        Node dummy = new Node("", 0, head);        Node prev = dummy;        while (prev.next != null) {            if (prev.next.key.equals("b")) {                prev.next = prev.next.next;                break;            }            prev = prev.next;        }        for (Node c = dummy.next; c != null; c = c.next) {            System.out.print(c.key + " ");        }        System.out.println();    }}
Output
c a 

What this code does

  • Dummy node simplifies deleting from the head or middle of a chain.
  • Unlinking node 'b' joins 'c' directly to 'a'.
  • The removed node becomes eligible for garbage collection.

Example 3 · Tracking Map Size and Key Membership

ChainedSizeDemo.javaJava
public class ChainedSizeDemo {    static class Node {        String key; int val; Node next;        Node(String k, int v, Node n) { key = k; val = v; next = n; }    }
    private Node[] buckets = new Node[4];    private int size = 0;
    public void put(String key, int val) {        int idx = (key.hashCode() % buckets.length + buckets.length) % buckets.length;        for (Node curr = buckets[idx]; curr != null; curr = curr.next) {            if (curr.key.equals(key)) { curr.val = val; return; }        }        buckets[idx] = new Node(key, val, buckets[idx]);        size++;    }
    public boolean containsKey(String key) {        int idx = (key.hashCode() % buckets.length + buckets.length) % buckets.length;        for (Node curr = buckets[idx]; curr != null; curr = curr.next) {            if (curr.key.equals(key)) return true;        }        return false;    }
    public int size() { return size; }
    public static void main(String[] args) {        ChainedSizeDemo map = new ChainedSizeDemo();        map.put("k1", 10);        map.put("k2", 20);        System.out.println("Size: " + map.size());        System.out.println("Contains k1: " + map.containsKey("k1"));        System.out.println("Contains k3: " + map.containsKey("k3"));    }}
Output
Size: 2
Contains k1: true
Contains k3: false

What this code does

  • size increments only when a genuinely new key is inserted.
  • containsKey traverses the matching bucket chain in O(1) average time.
  • Missing key 'k3' evaluates bucket chain and returns false cleanly.

put(key, value) computes the bucket index and traverses the chain. If the key is found, update its value; otherwise append a new Node. get(key) scans the chain and returns the matching value or null. remove(key) unlinks the matching Node by updating the predecessor's next pointer. Consider capacity 4 with bucket indices 0 to 3. First, insert key 10 with value 'A'. 10 % 4 = 2, so bucket 2 receives node [10:A]. Next, insert key 14 with value 'B'. 14 % 4 = 2, colliding directly with key 10. We prepend node [14:B], making bucket 2 [14:B] -> [10:A]. Lookup get(10) hashes to bucket 2 and traverses the chain. It inspects 14, advances to 10, and returns 'A'.

  • put: updates existing key or inserts new node into the chain.
  • get: traverses chain comparing keys with .equals(), returning value.
  • remove: unlinks target node from the singly linked list.

Trace the code

Trace keys into buckets

public class ChainTrace {
public static void main(String[] args) {
int[] keys = {10, 14, 7};
String[] buckets = new String[4];
for (int key : keys) {
int index = key % 4;
if (buckets[index] == null) {
buckets[index] = "" + key;
} else {
buckets[index] = key + " -> " + buckets[index];
}
}
System.out.println("Bucket 2: " + buckets[2]);
System.out.println("Bucket 3: " + buckets[3]);
}
}

Variables

keys
[10, 14, 7]

Output

(nothing printed yet)

Line 3Three keys will be added to a table of four buckets.

Step 1 of 10

Deciding about null keys

A null key has no hash code, so calling key.hashCode() on it throws a NullPointerException. The helper below sends a null key to bucket 0 instead.

Java
private int getIndex(String key) {    if (key == null) return 0;     // null.hashCode() would throw NullPointerException    return (key.hashCode() % capacity + capacity) % capacity;}// In put and get, compare keys with Objects.equals(curr.key, key):// curr.key.equals(key) throws when the stored key is null

Custom maps must decide whether to support null keys at bucket index 0 or reject them. Explicit null checks keep custom map implementations predictable and safe. Standard Java HashMap also reserves bucket 0 for the null key.

  • Null key risk: calling null.hashCode() causes NullPointerException.
  • Dedicated bucket: map null keys to bucket 0 without computing a hash.
  • Rejection option: throw IllegalArgumentException when a key is null.

Fix the error

Fix the chain code

Read the real compiler error, then pick the line that fixes it.

Round 1 of 3

Create the first node of a chain.

public class NullKeyFix1 {
static class Node {
String key; int value; Node next;
Node(String k, int v, Node n) { key = k; value = v; next = n; }
}
public static void main(String[] args) {
Node head = new Node("cable", 12);
System.out.println(head.key);
}
}

Error

NullKeyFix1.java:8: error: constructor Node in class Node cannot be applied to given types;
        Node head = new Node("cable", 12);
                    ^
  required: String,int,Node

Next step

Check your understanding

10 quick questions