HashMap: Key-Value Pairs

HashMap: Key-Value Pairs in Java: A maintenance workshop keeps its expensive tooling behind a counter called the tool crib.

The Analogy: The Tag Board At A Tool-Crib Window

A maintenance workshop keeps its expensive tooling behind a counter called the tool crib. When a fitter wants a torque wrench she hands her brass ID tag through the hatch. The attendant hangs the tag on a numbered hook -- the hook number is the last two digits of her badge number -- and passes the wrench out. The tag on the hook is proof that badge 3847 has the wrench. Returning the tool is just as fast: the attendant looks at hook 47, finds her tag, and hands it back. The lookup is instant because the hook number is computed directly from the badge number, not discovered by scanning every hook on the board.

Two fitters can hash to the same hook. Badge 2247 and badge 3847 both point to hook 47. The crib handles this by hanging both tags on the same peg, one behind the other, and checking the full badge number whenever someone asks for a tag back. As long as most hooks hold only one tag the extra comparison is rare. But if the workshop hires faster than the board grows, several hooks end up with chains of three or four tags and every return visit slows down.

The crib manager watches utilisation. When seventy-five percent of hooks are occupied she orders a wider board -- two hundred hooks instead of one hundred -- and re-hangs every tag on its new hook number. Badge 3847 now goes to hook 147 on the wider board, not hook 47. The re-hang takes an afternoon, but once it is done the chains are short again and lookups are fast. She never re-hangs during a shift because tools would be unreachable while the board is half-moved.

The failure mode: the night-shift supervisor decides to record loans in a ruled exercise book instead, writing badge numbers in the order people arrive. Finding who has the torque wrench now means scanning the book line by line -- hundreds of entries on a busy night. The tag board existed precisely to avoid that linear scan, and the moment someone replaces it with an ordered list the constant-time guarantee disappears.


Syntax or Core Structure

import java.util.HashMap;
import java.util.Locale;
import java.util.TreeMap;

public class ToolCrib {
    public static void main(String[] args) {
        HashMap<Integer, String> loans = new HashMap<>();

        loans.put(3847, "Torque wrench");
        loans.put(2247, "Dial indicator");
        loans.put(1190, "Feeler gauge");
        loans.put(5005, "Micrometer");

        System.out.println("badge:    " + loans.get(3847));
        System.out.println("has 2247: " + loans.containsKey(2247));

        loans.remove(1190);
        System.out.println("size:     " + loans.size());

        loans.replace(5005, "Digital micrometer");
        System.out.println("replaced: " + loans.get(5005));

        System.out.println("missing:  "
            + loans.getOrDefault(9999, "NONE"));

        loans.putIfAbsent(3847, "Angle grinder");
        System.out.println("kept:     " + loans.get(3847));

        System.out.println("--- loans ---");
        new TreeMap<>(loans).forEach((k, v) ->
            System.out.println(
                String.format(Locale.ROOT,
                    "%-6d -> %s", k, v)));
    }
}

Output:

badge:    Torque wrench
has 2247: true
size:     3
replaced: Digital micrometer
missing:  NONE
kept:     Torque wrench
--- loans ---
2247   -> Dial indicator
3847   -> Torque wrench
5005   -> Digital micrometer

Technical Depth: How Buckets Are Chosen, Why hashCode And equals Must Agree, And What A Rehash Costs

How The Bucket Index Is Chosen

A HashMap stores entries in an internal array called the table. The table length is always a power of two -- sixteen by default. When you call put(key, value), the map computes the key's hashCode(), spreads the result with a secondary hash that mixes the upper bits into the lower bits, and masks it to a table index with h & (table.length - 1). Because the table length is a power of two the mask retains only the lowest bits, which is why the secondary hash exists -- without it, keys whose hash codes differ only in the upper bits would all land in the same bucket.

The bucket at that index is either empty, holds a single entry, or holds a chain of entries that all hashed to the same index. Each entry stores the original hash, the key, the value, and a pointer to the next entry in the chain. A get call repeats the same index calculation and then walks the chain, comparing the stored hash first (a cheap int comparison) and the full equals only when the hashes match.

The hashCode-equals Contract

Four rules govern every class that overrides either method.

RuleConsequence if broken
Equal objects must return the same hashCodeget finds the wrong bucket and returns null
Unequal objects may share a hashCodeCollisions increase but correctness is preserved
hashCode must be consistent across callsAn entry stored under one hash is never found under another
If equals is overridden hashCode must be tooObject.hashCode is identity-based so equal objects hash differently

The most common violation is overriding equals but forgetting hashCode. The program below creates two Tag objects that are logically equal but hash differently because Tag relies on the default identity-based hashCode.

import java.util.HashMap;

public class Contract {

    static final class Tag {
        final int number;
        Tag(int number) { this.number = number; }

        @Override
        public boolean equals(Object o) {
            return o instanceof Tag t
                && t.number == number;
        }
    }

    public static void main(String[] args) {
        HashMap<Tag, String> board = new HashMap<>();
        Tag a = new Tag(100);
        board.put(a, "Wrench");

        Tag b = new Tag(100);
        System.out.println("equals:   " + a.equals(b));
        System.out.println("lookup-b: "
            + board.getOrDefault(b, "MISSING"));
        System.out.println("lookup-a: "
            + board.getOrDefault(a, "MISSING"));
        System.out.println("size:     " + board.size());
    }
}

Output:

equals:   true
lookup-b: MISSING
lookup-a: Wrench
size:     1

Tags a and b are equal by equals, but Object.hashCode returns different values for different object instances, so b hashes to a different bucket and the lookup misses. Tag a still finds its own entry because the same object hashes consistently within a single JVM run.

Collision Handling And Treeification

When several keys land in the same bucket the map stores them as a linked chain. A lookup walks the chain comparing the cached hash and then equals. A short chain costs almost nothing, but a bucket that fills with many colliding keys degrades that bucket from constant time toward linear time. To defend against a pathological case -- often a deliberate one, where an attacker sends keys crafted to collide -- HashMap converts a bucket to a balanced red-black tree once its chain reaches eight entries and the table itself holds at least sixty-four slots. A treeified bucket looks up in logarithmic rather than linear time. If later removals shrink the bucket below six entries it reverts to a plain chain. Treeification only helps when keys are Comparable or a fallback ordering applies; it is a safety net, not a substitute for a well-distributed hashCode.

Load Factor And The Cost Of A Rehash

The load factor is the fraction of the table that may fill before the map grows. The default is 0.75, so a sixteen-slot table resizes when the thirteenth entry is added. Resizing allocates a new table of double the length and re-inserts every existing entry at its new index -- an O(n) operation. Because resizes double the capacity, they happen geometrically less often as the map grows, so the amortised cost of a single put stays O(1). The 0.75 default trades a little wasted space for short chains; a higher factor saves memory but lengthens chains, and a lower factor does the reverse. If you know the final size, presize the map so no resize ever happens: pass an initial capacity of at least expectedSize / 0.75 + 1. Note that the internal table never shrinks -- a map that once held a million entries keeps its large table even after every entry is removed.

Null Keys And The Ambiguity Of get

HashMap permits exactly one null key (stored in bucket zero, bypassing the hash calculation) and any number of null values. That flexibility introduces an ambiguity: a null returned from get means either the key is absent or the key is present and mapped to null. The two cases are indistinguishable without a second call.

import java.util.HashMap;

public class NullMap {
    public static void main(String[] args) {
        HashMap<String, String> m = new HashMap<>();
        m.put("bolt", null);
        m.put("nut", "M8");
        m.put(null, "spare");

        System.out.println("bolt:     " + m.get("bolt"));
        System.out.println("missing:  " + m.get("washer"));
        System.out.println("has bolt: " + m.containsKey("bolt"));
        System.out.println("has wash: " + m.containsKey("washer"));
        System.out.println("null key: " + m.get(null));
        System.out.println("size:     " + m.size());
    }
}

Output:

bolt:     null
missing:  null
has bolt: true
has wash: false
null key: spare
size:     3

Both bolt and washer return null from get, yet containsKey distinguishes them. When a null value is meaningful, pair get with containsKey or store a sentinel instead of null. getOrDefault does not resolve the ambiguity -- a key mapped to null still returns null, not the default.

Choosing The Right Map

HashMap is one of several map implementations, each with a different guarantee.

ImplementationIteration orderNull keyTypical use
HashMapNone (bucket layout)One allowedDefault unordered access
LinkedHashMapInsertion or access orderOne allowedOrdered iteration, LRU caches
TreeMapSorted by keyNot allowedRange queries, sorted output
EnumMapEnum declaration orderNot allowedEnum keys only
ConcurrentHashMapNoneNot allowedShared state across threads

The rule of thumb: reach for HashMap by default, switch to LinkedHashMap the moment iteration order matters, TreeMap when you need keys sorted, and ConcurrentHashMap the moment more than one thread writes.


Real World Example: A Tool Crib Where A Clerical Update Orphaned A Loan

The tool crib tracks live loans in a HashMap<Badge, String>. The Badge class overrides hashCode and equals over both its number and its department. That looks careful, but the department field is mutable, and when the office reassigns a fitter to a new department it updates the same Badge object that is already sitting in the map as a key. The object now hashes to a different bucket than the one it was filed under, so the loan becomes unreachable through a normal lookup even though it is still physically in the map.

import java.util.HashMap;
import java.util.Locale;
import java.util.Objects;
import java.util.TreeMap;

public class CribRegister {

    static final class Badge {
        final int number;
        String department;

        Badge(int number, String department) {
            this.number = number;
            this.department = department;
        }

        @Override
        public boolean equals(Object o) {
            return o instanceof Badge b
                && b.number == number
                && Objects.equals(b.department, department);
        }

        @Override
        public int hashCode() {
            return Objects.hash(number, department);
        }
    }

    public static void main(String[] args) {
        HashMap<Badge, String> loans = new HashMap<>();
        Badge alice = new Badge(3847, "Mech");
        Badge omar = new Badge(2247, "Elec");
        loans.put(alice, "Torque wrench");
        loans.put(omar, "Megger");

        String before = loans.getOrDefault(alice, "LOST");
        System.out.println("before:   " + before);

        // The office reassigns Alice. The key object mutates.
        alice.department = "Inst";

        String after = loans.getOrDefault(alice, "LOST");
        System.out.println("after:    " + after);
        System.out.println("size:     " + loans.size());

        // A fresh lookup with the original details also fails:
        // the stored entry now carries department Inst.
        Badge probe = new Badge(3847, "Mech");
        System.out.println("probe:    "
            + loans.getOrDefault(probe, "LOST"));

        System.out.println("--- walk ---");
        TreeMap<Integer, String> byNumber = new TreeMap<>();
        loans.forEach((b, tool) ->
            byNumber.put(b.number, b.department + " " + tool));
        byNumber.forEach((n, v) ->
            System.out.println(
                String.format(Locale.ROOT, "%-6d %s", n, v)));
    }
}

Output:

before:   Torque wrench
after:    LOST
size:     2
probe:    LOST
--- walk ---
2247   Elec Megger
3847   Inst Torque wrench

The entry never left the map -- size stays at 2 and the walk still lists both loans. What broke is the map's one non-negotiable assumption: a key's hash code must not change while the key is in the map. Mutating alice.department moved the key's hash to a new bucket without moving the entry, so every future lookup searches the wrong bucket. The entry is now an orphan -- reachable by iteration, unreachable by key.

The probe lookup fails for a second, subtler reason. Even after the mutation, the stored entry's key is the same alice object, which now reports department "Inst". A fresh Badge built with the original "Mech" is not equal to it, so it does not match either. There is no combination of number and department that both hashes to the right bucket and equals the stored key -- the object's identity as a key has been destroyed in place.

The fix is to make Badge immutable: mark department final and issue a new Badge when someone is reassigned, then re-key the map explicitly by removing the old entry and putting the new one. Strings, boxed primitives, enums, and records with final components are safe as keys precisely because they cannot mutate underneath the map. When a custom class must be a key, every field that participates in hashCode and equals should be final.

The genuine limit worth stating plainly is that Java enforces none of this. The compiler will happily let a mutable object be a map key and will not warn when its state changes; the map has no way to detect that a key it is holding has shifted buckets. The design flaw in this register is not the mutation itself but the decision to key the map on an object whose fields the rest of the system freely edits. A quieter flaw hides in the walk: it assumes no null key was ever inserted, but HashMap accepts one silently, so a stray put(null, ...) elsewhere would throw a NullPointerException inside b.number here with no hint of where the null came from.


Common Mistakes

  1. Overriding equals without hashCode. Logically equal objects hash to different buckets, so get and containsKey miss entries that are demonstrably present. Always override both together, over the same fields.
  1. Mutating a key after inserting it. Changing any field used by hashCode moves the key to a new bucket while the entry stays behind, orphaning it. Use immutable keys, or objects whose hash-relevant fields never change.
  1. Treating a null from get as "key absent". A key mapped to null returns the same null as a missing key. Use containsKey when the distinction matters, or never store null values.
  1. Assuming iteration order is stable. HashMap iteration order reflects bucket layout, which changes across resizes and JVM versions. Never assert on toString or iteration order; use LinkedHashMap or TreeMap when order matters.
  1. Sizing initial capacity to the exact element count. A map created with capacity 100 still resizes at 75 entries because the threshold is capacity times load factor. Pass expectedSize / 0.75 + 1 to avoid the resize entirely.
  1. Using get-then-put where merge or compute fits. Two separate bucket lookups where one would do, and not atomic under concurrency. merge, compute, and computeIfAbsent do it in a single traversal.
  1. Wrapping a HashMap in synchronizedMap and assuming it is thread-safe. Each method call is synchronised, but a check-then-act sequence across two calls still races. Use ConcurrentHashMap and its atomic methods instead.
  1. Sharing a plain HashMap across threads without synchronisation. A concurrent write during a resize can corrupt the table; on older JVMs a reader could spin forever. Use ConcurrentHashMap or publish an unmodifiable snapshot.
  1. Relying on an expensive hashCode. The hash is computed on every put, get, and remove, so a slow or poorly distributed hash function degrades every operation. Keep it fast and well spread.

Best Practices

  • Use immutable objects as keys. Strings, boxed primitives, enums, and records with final components are inherently safe; for a custom class, make every field in hashCode and equals final.
  • Presize the map when the final count is known. An initial capacity of expectedSize / 0.75 + 1 removes every interim resize and its O(n) rehash.
  • Prefer getOrDefault over a get-then-null-check. Reserve containsKey for when a stored null must be told apart from an absent key.
  • Reach for merge, compute, and computeIfAbsent on update-in-place patterns. Counting or grouping is one traversal that reads more clearly than get-then-put.
  • Choose the implementation by requirement. HashMap for unordered access, LinkedHashMap for insertion order, TreeMap for sorted keys, EnumMap for enum keys, ConcurrentHashMap for shared writes.
  • Generate hashCode and equals from the same field set. An IDE, Objects.hash, or a record does this correctly and keeps the two methods from drifting apart.
  • Never share a plain HashMap across threads. Use ConcurrentHashMap for concurrent writes, or hand out an unmodifiable snapshot for concurrent reads.
  • Keep hashCode cheap and well distributed. A constant hash turns the map into a linked list; a slow hash taxes every lookup.

Practice Exercises

  1. The Orphaned Loan. Write a ToolTag class with an int id and a mutable String section, overriding hashCode and equals over both fields. Put a ToolTag into a HashMap<ToolTag, String>, look it up successfully, then mutate its section and look it up again -- observe the miss. Then write an immutable variant with a final section and show that reassigning a tool now requires removing the old key and putting a new one, and that no entry is ever orphaned.
  1. The Count In One Pass. Given an array of badge-number strings with duplicates, build a HashMap<String, Integer> of counts. Do it first with get-then-put, then rewrite it with merge(key, 1, Integer::sum). Print both maps sorted by key through a TreeMap and confirm the counts match, then explain why the merge version performs one bucket lookup per element instead of two.
  1. The Ambiguous Null. Build a HashMap<String, String> where one key is deliberately mapped to null and another key is absent. Write a method status(map, key) that returns "absent", "null-value", or the actual value, using containsKey to tell the first two apart. Verify it against both keys and a normal entry, and explain why getOrDefault alone cannot distinguish the absent key from the null-valued one.