Programming Search⌘K

Conceptcore

Hash table

Also called hash map, hashmap, hash, hashtable, unordered map, bucket array, scatter table, HashMap, Hashtable, unordered_map.

A hash table stores keys in an array of buckets and uses the hash code of a key to find its bucket. Lookup, insert and remove take constant time on average.

Applies to
core-languages

Idea

A hash table is the usual way to build a map or a set. It keeps an array of buckets. To store a key, the table computes a number from the key, the hash code, and uses the number to choose a bucket. To find the key again, it computes the same number and looks in the same bucket only. Wikipedia says: "A hash table uses a hash function to compute an index, also called a hash code, into an array of buckets or slots, from which the desired value can be found"1.

This page is about hash tables as a programmer uses them: what a key must do, why the order of the keys changes, and when a table grows. The algorithms inside a hash table are on the algorithm site: hash table, separate chaining and open addressing.

# A small hash table with chaining: each bucket is a list of (key, value) pairs.
class Table:
    def __init__(self, size=8):
        self.buckets = [[] for _ in range(size)]
        self.count = 0

    def index(self, key):
        return hash(key) % len(self.buckets)

    def put(self, key, value):
        bucket = self.buckets[self.index(key)]
        for i, (k, _) in enumerate(bucket):
            if k == key:
                bucket[i] = (key, value)
                return
        bucket.append((key, value))
        self.count += 1
        if self.count / len(self.buckets) > 0.75:
            self.resize(2 * len(self.buckets))

    def get(self, key):
        for k, v in self.buckets[self.index(key)]:
            if k == key:
                return v
        raise KeyError(key)

    def resize(self, size):
        old = self.buckets
        self.buckets = [[] for _ in range(size)]
        for bucket in old:
            for k, v in bucket:
                self.buckets[self.index(k)].append((k, v))

    def show(self):
        return {i: [k for k, _ in b] for i, b in enumerate(self.buckets) if b}


# hash(n) is n for a small int, so the bucket is n % 8. 3, 11 and 19 collide.
t = Table()
for key in [3, 11, 19, 5, 8]:
    t.put(key, key * 10)
print(t.show())
print(t.get(19), t.count / len(t.buckets))

# The seventh key makes the load factor 7/8, which is more than 0.75.
t.put(4, 40)
t.put(6, 60)
print(len(t.buckets), t.show())
Output
{0: [8], 3: [3, 11, 19], 5: [5]}
190 0.625
16 {3: [3, 19], 4: [4], 5: [5], 6: [6], 8: [8], 11: [11]}

The keys 3, 11 and 19 have the same remainder after division by 8, so they share bucket 3. A lookup of 19 looks at bucket 3 only and compares 19 with the three keys there. After the seventh key, the table doubles to 16 buckets and puts each key again. Now 11 is in bucket 11, and the order of the keys in the table is different.

How it works

Hash, then compare. A lookup has two steps. The table hashes the key to find a bucket, and then it compares the key with each key in that bucket. Two different keys can have the same hash code or the same bucket. Wikipedia notes that "Most hash table designs employ an imperfect hash function"1, so the table must handle these collisions. "Common strategies to handle hash collisions include separate chaining, which stores multiple elements in the same slot using linked lists, and open addressing, which searches for the next available slot according to a probing sequence"1. The example above uses separate chaining. Python, Rust and Go use open addressing.

The rule for keys. Because the table compares keys only inside one bucket, two equal keys must go to the same bucket. So equal keys must have equal hash codes. Java states the rule: "If two objects are equal according to the equals method, then calling the hashCode method on each of the two objects must produce the same integer result"2. Python says "The only required property is that objects which compare equal have the same hash value"3. The reverse is not necessary. .NET notes that "equal hash codes do not imply object equality, because different (unequal) objects can have identical hash codes"4. A type that breaks the rule gives a table that cannot find its own keys. See hash codes and value equality and identity.

The load factor. "The efficiency of a hash table depends on the load factor (α), defined as the ratio of the number of stored elements to the number of available slots"1. With more keys for each bucket, a lookup compares more keys. So a table grows when the load factor passes a limit. Java HashMap grows when "the number of entries in the hash table exceeds the product of the load factor and the current capacity"5, to "approximately twice the number of buckets"5, and "the default load factor (.75) offers a good tradeoff between time and space costs"5. C++ grows "if the load factor exceeds this threshold"6, and its default maximum load factor is 1.

Resize and order. A larger table moves every key. "The items cannot simply be copied over into the same indices since the hash function depends on the table size"1. This is why a hash table has no stable order: the order of a loop follows the buckets, and the buckets change when the table grows. Java HashMap "makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time"5. A program that needs an order uses an insertion-ordered map or an ordered map.

Seeds. Some languages add a random seed to the hash function. Then the same keys go to different buckets in each run. Rust: "By default, HashMap uses a hashing algorithm selected to provide resistance against HashDoS attacks. The algorithm is randomly seeded"7. In Python, "the hash() values of str and bytes objects are “salted” with an unpredictable random value"3. The seed protects a server from an attacker who sends many keys with the same hash code. The attack is on the algorithm site: algorithmic complexity attack.

In languages

LanguageVerdictNote
PythonNative
C++Standard library
JavaStandard library
CIdiom
C#Standard library
JavaScriptNative
TypeScriptNativeTypeScript uses the JavaScript Map and Set. The language gives no hash code to a program, and object keys are compared by identity. No example file exists.
GoNative
RustStandard library
KotlinStandard libraryHashMap, HashSet and the default LinkedHashMap come from the JVM. A data class defines equals and hashCode from its properties, so it is a safe key. No example file exists because kotlinc is not installed.
SQLIdiomA database can store an index as a hash index, as with CREATE INDEX ... USING HASH in PostgreSQL, and a query planner can use a hash join. The program does not handle the buckets.
BashNativeAn associative array made with declare -A is a hash table inside Bash, with string keys. The shell does not show its buckets or hash function. No example file exists.
PowerShellNativeThe literal @{} makes a System.Collections.Hashtable, and keys use GetHashCode with a comparer that ignores case. No example file exists because pwsh is not installed.
HTMLDoes not applyHTML is markup and has no data structures.
CSSDoes not applyCSS has no data structures.
Regular expressionsDoes not applyA regular expression matches text. It has no hash tables.
Language Verdict Mechanism
Python native dict and set with open addressing; __hash__ and __eq__; str hashes salted for each process
JavaScript native Map and Set; no hash code for a program; keys compared with SameValueZero, objects by identity
TypeScript native the JavaScript Map and Set
Java stdlib HashMap, HashSet and LinkedHashMap with chaining; hashCode and equals; load factor 0.75
Kotlin stdlib the JVM HashMap and HashSet; a data class defines equals and hashCode
C# stdlib Dictionary<TKey,TValue> and HashSet<T>; GetHashCode and Equals, or an IEqualityComparer<T>
Go native the built-in map, a Swiss table; keys of any comparable type
Rust stdlib HashMap and HashSet; the traits Hash and Eq; SipHash 1-3 with a random seed by default
C idiom no hash table in the standard library; POSIX hsearch, or a hand-written table
C++ stdlib std::unordered_map and std::unordered_set with buckets; std::hash or a user hash functor
Bash native associative arrays from declare -A, with no access to the buckets
PowerShell native @{} is a System.Collections.Hashtable with keys that ignore case
SQL idiom hash indexes and hash joins inside the database
Regex n/a patterns match text and have no hash tables
HTML n/a markup with no data structures
CSS n/a style rules with no data structures

JavaScript does not say how a Map works inside. MDN quotes the specification: a map must be implemented with mechanisms "that, on average, provide access times that are sublinear on the number of elements in the collection"8. In practice the engines use hash tables. C++ is the most open: std::unordered_map keeps "key-value pairs with unique keys", and "Which bucket an element is placed into depends entirely on the hash of its key. Keys with the same hash code appear in the same bucket"9. A program can read the number of buckets, the bucket of a key and the load factor.

Go changed its map in Go 1.24. "Go 1.24 includes a completely new implementation of the built-in map type, based on the Swiss Table design"10. A Swiss table uses open addressing, but it breaks the array "into logical groups of 8 slots each"10, and each group has a control word with 7 bits of the hash for each slot, so a lookup tests 8 slots with a few instructions. The blog calls this "an operation supported by SIMD hardware"10. The Swiss table page on the algorithm site has the details.

The example files show these forms. Python shows the hash of small ints, the rule for __eq__ and __hash__, and a constant hash that makes each lookup a scan. JavaScript shows SameValueZero and object keys by identity. Java shows that "Aa" and "BB" both have the hash code 2112, a class that overrides equals only, a record, and HashMap.newHashMap. C# counts the calls to Equals for a constant hash code: 1000 inserts make 499500 calls, and one lookup makes 500 more. Go shows NaN keys, 0.0 and -0.0, a size hint and a key that cannot be hashed. Rust shows derive(Hash), two RandomState seeds and with_capacity. C writes a chained table that doubles. C++ shows the bucket interface, reserve and rehash.

PythonGitHub
# hash() of a small int is the int itself, and -1 is a special case.
print(hash(42), hash(-1), hash(-2))

# Equal numbers have equal hashes, so 1, 1.0 and True find the same entry.
print(hash(1) == hash(1.0) == hash(True), {1: "a"}[1.0])

# A str hash is salted per process: it is stable in one run, not across runs.
print(hash("key") == hash("key"))


# A key class defines __eq__ and __hash__ from the same fields.
class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y

    def __eq__(self, other):
        return isinstance(other, Point) and (self.x, self.y) == (other.x, other.y)

    def __hash__(self):
        return hash((self.x, self.y))


print({Point(1, 2): "found"}[Point(1, 2)])


# A class with __eq__ and no __hash__ is not hashable.
class OnlyEq:
    def __eq__(self, other):
        return True


try:
    {OnlyEq(): 1}
except TypeError as e:
    print(type(e).__name__)


# A bad hash still works, but every key goes to one bucket, so each lookup is a linear scan.
class Bad:
    calls = 0

    def __init__(self, n):
        self.n = n

    def __eq__(self, other):
        Bad.calls += 1
        return self.n == other.n

    def __hash__(self):
        return 0


d = {Bad(i): i for i in range(200)}
print(len(d), d[Bad(150)], Bad.calls > 10000)
Output
42 -2 -2
True a
True
found
TypeError
200 150 True
  • Verdict: native. dict and set are hash tables. hash of a small int is the int, so equal numbers such as 1, 1.0 and True share a hash. A str hash is salted for each process. A key class defines eq and hash from the same fields, and a class with eq and no hash cannot be a key. A constant hash still works, but each lookup scans all keys.
#include <cstddef>
#include <functional>
#include <iostream>
#include <string>
#include <unordered_map>

struct Point {
    int x, y;
    bool operator==(const Point&) const = default;
};

// A hash functor for Point. It mixes the hashes of the fields.
struct PointHash {
    std::size_t operator()(const Point& p) const noexcept {
        std::size_t h = std::hash<int>{}(p.x);
        return h ^ (std::hash<int>{}(p.y) + 0x9e3779b9 + (h << 6) + (h >> 2));
    }
};

// A legal but bad hash: every key gets the same hash code.
struct ZeroHash {
    std::size_t operator()(int) const noexcept { return 0; }
};

int main() {
    std::unordered_map<Point, std::string, PointHash> grid{{{1, 2}, "found"}};
    std::cout << grid.at({1, 2}) << "\n";

    // The default maximum load factor is 1: on average one element per bucket.
    std::unordered_map<int, int> m;
    std::cout << m.max_load_factor() << "\n";
    for (int i = 0; i < 100; i++) m[i] = i * i;
    std::cout << (m.load_factor() <= m.max_load_factor()) << " " << (m.bucket_count() >= 100) << "\n";

    // Keys with the same hash share a bucket. A hash that returns 0 puts all keys in one.
    std::unordered_map<int, int, ZeroHash> same;
    for (int i = 0; i < 10; i++) same[i] = i;
    std::cout << same.bucket_size(same.bucket(3)) << " " << same.at(7) << "\n";

    // reserve makes room for n elements, so the next n inserts do not rehash.
    std::unordered_map<int, int> sized;
    sized.reserve(1000);
    std::size_t before = sized.bucket_count();
    for (int i = 0; i < 1000; i++) sized[i] = i;
    std::cout << (sized.bucket_count() == before) << "\n";

    // A rehash moves the elements, so it invalidates iterators, but not pointers to elements.
    int* p = &m[7];
    m.rehash(4096);
    std::cout << *p << " " << (m.bucket_count() >= 4096) << "\n";
}
Output
found
1
1 1
10 7
1
49 1
  • Verdict: stdlib. std::unordered_map takes a hash functor for a user type. It exposes its buckets: bucket_count, bucket, bucket_size, load_factor and max_load_factor, which is 1 by default. reserve and rehash set the number of buckets. A rehash keeps pointers to elements valid.
JavaGitHub
import java.util.HashMap;
import java.util.Map;

public class Main {
  // A class that overrides equals but not hashCode breaks the hash table contract.
  static final class BadPoint {
    final int x, y;
    BadPoint(int x, int y) { this.x = x; this.y = y; }
    @Override public boolean equals(Object o) {
      return o instanceof BadPoint p && p.x == x && p.y == y;
    }
  }

  // A record gets equals and hashCode from its fields.
  record Point(int x, int y) {}

  public static void main(String[] args) {
    // String.hashCode is s[0]*31^(n-1) + ... + s[n-1], so "Aa" and "BB" collide.
    System.out.println("Aa".hashCode() + " " + "BB".hashCode());
    Map<String, Integer> m = new HashMap<>();
    m.put("Aa", 1);
    m.put("BB", 2);
    System.out.println(m.get("Aa") + " " + m.get("BB") + " " + m.size());

    // Equal BadPoints usually have different hash codes, so the lookup misses.
    Map<BadPoint, String> bad = new HashMap<>();
    bad.put(new BadPoint(1, 2), "found");
    System.out.println(new BadPoint(1, 2).equals(new BadPoint(1, 2)) + " " + bad.get(new BadPoint(1, 2)));

    Map<Point, String> good = new HashMap<>();
    good.put(new Point(1, 2), "found");
    System.out.println(good.get(new Point(1, 2)) + " " + (new Point(1, 2).hashCode() == new Point(1, 2).hashCode()));

    // The default capacity is 16 and the load factor is 0.75, so the 13th entry makes the table grow.
    // A capacity given at the start avoids the copies: 1000 entries need 1000 / 0.75 buckets.
    Map<Integer, Integer> sized = HashMap.newHashMap(1000);
    for (int i = 0; i < 1000; i++) sized.put(i, i * i);
    System.out.println(sized.get(999));
  }
}
Output
2112 2112
1 2 2
true null
found true
998001
  • Verdict: stdlib. HashMap uses hashCode to find a bucket and equals to find the key. "Aa" and "BB" have the same hash code, 2112, and the map keeps both. A class that overrides equals and not hashCode is lost in the map. A record defines both. HashMap.newHashMap(n) sizes the table for n entries at the default load factor of 0.75.
#define _POSIX_C_SOURCE 200809L /* for strdup before C23 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* A hash table with separate chaining and string keys. */
typedef struct entry {
    char *key;
    int value;
    struct entry *next;
} entry;

typedef struct {
    entry **buckets;
    size_t size, count;
} table;

/* FNV-1a: a simple 32-bit string hash. */
static unsigned fnv1a(const char *s) {
    unsigned h = 2166136261u;
    for (; *s; s++) {
        h ^= (unsigned char)*s;
        h *= 16777619u;
    }
    return h;
}

static void init(table *t, size_t size) {
    t->buckets = calloc(size, sizeof *t->buckets);
    t->size = size;
    t->count = 0;
}

static void grow(table *t) {
    table bigger;
    init(&bigger, t->size * 2);
    for (size_t i = 0; i < t->size; i++) {
        entry *e = t->buckets[i];
        while (e) {
            entry *next = e->next;
            size_t j = fnv1a(e->key) % bigger.size;
            e->next = bigger.buckets[j];
            bigger.buckets[j] = e;
            e = next;
        }
    }
    free(t->buckets);
    bigger.count = t->count;
    *t = bigger;
}

static void put(table *t, const char *key, int value) {
    size_t i = fnv1a(key) % t->size;
    for (entry *e = t->buckets[i]; e; e = e->next) {
        if (strcmp(e->key, key) == 0) {
            e->value = value;
            return;
        }
    }
    entry *e = malloc(sizeof *e);
    e->key = strdup(key);
    e->value = value;
    e->next = t->buckets[i];
    t->buckets[i] = e;
    /* Keep the load factor count / size at 0.75 or less. */
    if (++t->count * 4 > t->size * 3) grow(t);
}

static int *get(table *t, const char *key) {
    for (entry *e = t->buckets[fnv1a(key) % t->size]; e; e = e->next)
        if (strcmp(e->key, key) == 0) return &e->value;
    return NULL;
}

static void show(const table *t) {
    printf("%zu buckets:", t->size);
    for (size_t i = 0; i < t->size; i++) {
        size_t n = 0;
        for (entry *e = t->buckets[i]; e; e = e->next) n++;
        printf(" %zu", n);
    }
    printf("\n");
}

int main(void) {
    const char *words[] = {"apple", "banana", "cherry", "date", "elder", "fig", "grape"};
    table t;
    init(&t, 8);
    for (int i = 0; i < 6; i++) put(&t, words[i], i);
    show(&t);
    put(&t, "grape", 6); /* 7 > 0.75 * 8, so the table doubles */
    show(&t);
    put(&t, "fig", 50); /* an update, not a new entry */
    int *v = get(&t, "fig");
    printf("%d %zu %s\n", v ? *v : -1, t.count, get(&t, "kiwi") ? "found" : "missing");
    for (size_t i = 0; i < t.size; i++) {
        entry *e = t.buckets[i];
        while (e) {
            entry *next = e->next;
            free(e->key);
            free(e);
            e = next;
        }
    }
    free(t.buckets);
    return 0;
}
Output
8 buckets: 2 1 0 0 0 1 0 2
16 buckets: 2 0 0 0 0 1 0 1 1 1 0 0 0 0 0 1
50 7 missing
  • Verdict: idiom. C has no hash table in its standard library. This example writes one with separate chaining, the FNV-1a hash and a table that doubles when the load factor passes 0.75. POSIX hsearch gives one table for each program.
using System;
using System.Collections.Generic;

// A record struct gets Equals and GetHashCode from its fields.
var byValue = new Dictionary<Point, string> { [new Point(1, 2)] = "found" };
Console.WriteLine(byValue[new Point(1, 2)]);

// A class without overrides is a key by reference, so an equal-looking key misses.
var byRef = new Dictionary<RefPoint, string> { [new RefPoint(1, 2)] = "found" };
Console.WriteLine(byRef.ContainsKey(new RefPoint(1, 2)));

// A constant hash code is legal but puts every key in one bucket.
// Each insert then compares the new key with all keys that are already there.
var bad = new Dictionary<BadKey, int>();
for (int i = 0; i < 1000; i++) bad[new BadKey(i)] = i;
Console.WriteLine($"{bad[new BadKey(500)]} {BadKey.Calls}");

// EnsureCapacity sizes the table once, before many inserts.
var sized = new Dictionary<int, int>();
Console.WriteLine(sized.EnsureCapacity(1000) >= 1000);

// string.GetHashCode is randomized per process in .NET, so do not store it.
Console.WriteLine("key".GetHashCode() == "key".GetHashCode());

readonly record struct Point(int X, int Y);

sealed class RefPoint(int x, int y)
{
    public int X { get; } = x;
    public int Y { get; } = y;
}

sealed class BadKey(int n) : IEquatable<BadKey>
{
    public static long Calls;
    public int N { get; } = n;
    public bool Equals(BadKey? other)
    {
        Calls++;
        return other is not null && other.N == N;
    }
    public override bool Equals(object? obj) => Equals(obj as BadKey);
    public override int GetHashCode() => 0;
}
Output
found
False
500 500000
True
True
  • Verdict: stdlib. Dictionary uses GetHashCode to find a bucket and Equals to find the key. A record struct defines both from its fields, and a class without overrides is a key by reference. A constant hash code makes 1000 inserts call Equals 499500 times. EnsureCapacity sizes the table once.
JavaScriptGitHub
// A Map compares keys with SameValueZero. JavaScript gives no hash code to a program.
const m = new Map();
m.set(NaN, "nan");
m.set(0, "zero");
console.log(m.get(NaN), m.get(-0), m.size);

// Objects are keys by identity: two objects with the same fields are two keys.
const a = { x: 1, y: 2 };
const b = { x: 1, y: 2 };
const byObject = new Map([[a, "a"]]);
console.log(byObject.get(a), byObject.get(b));

// To look up by value, make a string key from the fields.
const key = (p) => `${p.x},${p.y}`;
const byValue = new Map([[key(a), "found"]]);
console.log(byValue.get(key(b)));

// A key object that changes keeps its entry, because identity does not change.
a.x = 99;
console.log(byObject.get(a));

// A WeakMap holds its object keys weakly, and primitive keys are an error.
const wm = new WeakMap();
wm.set(a, 1);
try {
  wm.set("s", 1);
} catch (e) {
  console.log(e.constructor.name);
}
Output
nan zero 2
a undefined
found
a
TypeError
  • Verdict: native. Map and Set are hash tables in the engines, but the language gives no hash code to a program. Keys are compared with SameValueZero, so NaN finds NaN and -0 finds 0. Objects are keys by identity, so a program that wants keys by value makes a string key from the fields.
package main

import (
	"fmt"
	"math"
)

type point struct{ x, y int }

func main() {
	// A struct of comparable fields is a key. Go hashes and compares all its fields.
	grid := map[point]string{{1, 2}: "found"}
	fmt.Println(grid[point{1, 2}])

	// NaN is not equal to itself, so each NaN insert adds a new entry
	// and no lookup finds it again.
	m := map[float64]int{}
	m[math.NaN()] = 1
	m[math.NaN()] = 2
	v, ok := m[math.NaN()]
	fmt.Println(len(m), v, ok)

	// clear removes all entries, including the NaN keys that delete cannot reach.
	clear(m)
	fmt.Println(len(m))

	// 0.0 and -0.0 are equal, so they are one key.
	m[0.0] = 1
	m[math.Copysign(0, -1)] = 2
	fmt.Println(len(m), m[0])

	// A size hint makes room for 1000 entries before the first insert.
	big := make(map[int]int, 1000)
	for i := range 1000 {
		big[i] = i * i
	}
	fmt.Println(len(big), big[999])

	// An interface key that holds a slice panics at run time, because a slice cannot be hashed.
	keys := map[any]int{}
	defer func() { fmt.Println("panic:", recover()) }()
	keys[[]int{1}] = 1
}
Output
found
2 0 false
0
1 2
1000 998001
panic: runtime error: hash of unhashable type []int
  • Verdict: native. Go hashes and compares keys of any comparable type, such as a struct. NaN keys are never found again, and only clear removes them. 0.0 and -0.0 are one key. make with a size hint makes room before the inserts. An interface key that holds a slice panics, because a slice cannot be hashed. Since Go 1.24 the map is a Swiss table.
RustGitHub
use std::collections::HashMap;
use std::hash::{BuildHasher, RandomState};

// derive(Hash, PartialEq, Eq) makes hash and equality agree, field by field.
#[derive(Hash, PartialEq, Eq, Debug)]
struct Point {
    x: i32,
    y: i32,
}

fn main() {
    let mut grid = HashMap::new();
    grid.insert(Point { x: 1, y: 2 }, "found");
    println!("{:?}", grid.get(&Point { x: 1, y: 2 }));

    // Each RandomState has its own random keys, so one value hashes differently in two maps.
    let s1 = RandomState::new();
    let s2 = RandomState::new();
    println!("{} {}", s1.hash_one("key") == s1.hash_one("key"), s1.hash_one("key") == s2.hash_one("key"));

    // with_capacity makes room for 1000 entries with no resize.
    let mut m: HashMap<i32, i32> = HashMap::with_capacity(1000);
    let cap = m.capacity();
    for i in 0..1000 {
        m.insert(i, i * i);
    }
    println!("{} {} {}", cap >= 1000, m.capacity() == cap, m[&999]);

    // f64 does not implement Eq or Hash, because NaN != NaN.
    // HashMap<f64, i32> does not compile; a common fix is to use the bits as the key.
    let mut by_bits: HashMap<u64, &str> = HashMap::new();
    by_bits.insert(1.5f64.to_bits(), "one and a half");
    println!("{:?}", by_bits.get(&1.5f64.to_bits()));

    // Hash is defined for tuples, strings and Vec, so they are keys too.
    let mut pairs: HashMap<(String, Vec<u8>), i32> = HashMap::new();
    pairs.insert(("a".to_string(), vec![1, 2]), 7);
    println!("{}", pairs[&("a".to_string(), vec![1, 2])]);
}
Output
Some("found")
true false
true true 998001
Some("one and a half")
7
  • Verdict: stdlib. derive(Hash, PartialEq, Eq) makes a struct a key. Each RandomState has random keys, so one value hashes differently in two maps. with_capacity makes room for n entries. f64 is not Eq or Hash, so a program uses the bits of a float as the key.
  • Separate chaining. Each bucket holds a list of entries. Java HashMap and C++ std::unordered_map use chains. When many keys collide and the keys are Comparable, Java HashMap "may use comparison order among keys to help break ties"5. See separate chaining.
  • Open addressing. All entries are in one array. A collision moves to another slot by a probe sequence. Python dict, Rust HashMap and Go map use open addressing. See open addressing.
  • Hash sets. A set is a hash table with keys and no values. HashSet in Java, C# and Rust and set in Python work the same way as their maps.
  • Size hints. A program that knows the number of keys can size the table at the start: HashMap.newHashMap(n) in Java, EnsureCapacity in C#, make(map[K]V, n) in Go, with_capacity in Rust and reserve in C++. This avoids the copies of each resize.
  • Custom hashers. Rust and C++ take the hash function as a type parameter, and C# takes an IEqualityComparer<T>. A program can use a faster hash for trusted keys, or a hash that ignores case.
  • Perfect hashing. For a fixed set of keys, such as the keywords of a language, a generator such as gperf makes a hash function with no collisions. See perfect hashing.

Pitfalls

  • Equals without hash. In Java and C#, a class that overrides equals or Equals and not hashCode or GetHashCode breaks the rule. Two equal keys usually go to different buckets, so get returns null for a key that looks present. Define both, or use a record. In Python, a class that defines __eq__ and not __hash__ cannot be a key at all.
  • A key that changes. The table stores a key in the bucket of its hash at the time of the insert. If a field that the hash uses changes, the key is in the wrong bucket and the table does not find it. Use immutable keys. See map and dictionary.
  • A bad hash. A hash function that gives the same value to many keys puts them in one bucket, and each lookup becomes a linear scan. Java warns that "using many keys with the same hashCode() is a sure way to slow down performance of any hash table"5. In the C# example, 1000 keys with a constant hash code make 499500 calls to Equals.
  • Depending on the order. The order of a loop over a hash table depends on the hash codes, the size of the table and, in some languages, a random seed. It can change between runs, between versions and after a resize. Sort the keys, or use an ordered map.
  • Stored hash codes. A hash code is for one table in one process. Java says that the hash code "need not remain consistent from one execution of an application to another execution of the same application"2, and .NET randomizes string hash codes in each process. Do not write hash codes to a file or use them as IDs.
  • NaN keys. NaN is not equal to itself. In Go, each m[NaN] = v adds a new entry that no lookup finds. Rust does not let f64 be a key at all. JavaScript Map treats NaN as one key.
  • Iterators after a resize. An insert can resize the table and move the entries. In C++, a rehash invalidates the iterators of an unordered_map. Pointers and references to the elements stay valid.

Cost

Operation Average Worst case
lookup constant linear in the number of keys
insert constant, amortized linear
remove constant linear
resize linear (rare) linear
loop over all keys linear in the keys plus the buckets same
memory the entries plus empty slots: at a load factor of 0.75 or less, at least 4 slots for each 3 entries same

"In a well-dimensioned hash table, the average time complexity for each lookup is independent of the number of elements stored in the table"1. The worst case comes from many keys in one bucket. In Java, a loop over a HashMap takes time in proportion to the capacity, which is the number of buckets, plus the number of entries5. A table that was large and is now almost empty is slow to loop over.

A hash table also has costs that the table above does not show. Each operation computes a hash, and a long string key takes time linear in its length. Each lookup compares the key with at least one stored key. For a few keys, a linear search in an array can be faster. The resizes cost linear time in total, as for a dynamic array, because the table doubles each time.

History

"In January 1953, Hans Peter Luhn wrote an internal IBM memorandum that used hashing with chaining"1. About the same time, a team at IBM Research "implemented hashing for the IBM 701 assembler"1. Wikipedia credits the first published use of the word hashing to an article by Robert Morris1.

Scripting languages made hash tables a part of the language: AWK arrays, Perl hashes and Python dicts. Java had Hashtable in version 1.0 and added HashMap in 1.2, and C++ added std::unordered_map in C++11. Newer designs use the cache of the processor better. "In 2017, Sam Benzaquen, Alkis Evlogimenos, Matt Kulukundis, and Roman Perepelitsa at Google presented a new C++ hash table design, dubbed “Swiss Tables”"10. Rust's HashMap is "implemented with quadratic probing and SIMD lookup"7, and Go moved to Swiss tables in Go 1.2410.

References

  1. Hash table, Wikipedia, Introduction; Load factor; Collision resolution; Dynamic resizing; History
  2. Class Object, Java SE 25 API, hashCode
  3. Data model, The Python Language Reference, object.__hash__
  4. Object.GetHashCode method, .NET API reference, Remarks
  5. Class HashMap, Java SE 25 API, Description
  6. std::unordered_map::max_load_factor, cppreference.com, Description
  7. Struct HashMap, The Rust Standard Library, Description
  8. Map, MDN Web Docs, Description; Key equality
  9. std::unordered_map, cppreference.com, Description
  10. Michael Pratt, Faster Go maps with Swiss Tables, The Go Blog, 2025, Full text

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/4091XS/text.yaml