Programming Search⌘K

Conceptcore

The equality and hashing contract

Also called equals and hashCode contract, hashCode contract, equals contract, Eq and Hash, hash consistency, equal objects equal hashes.

The equality and hashing contract is the rule that equality must be an equivalence relation and that equal objects must have equal hash codes, which hash tables need to find their keys.

Applies to
core-languages

Idea

A hash table finds a key in two steps. It computes the hash code of the key to choose a bucket, and then it calls equality on the keys in that bucket. The two steps give the same answer only if the type keeps one rule: equal objects have equal hash codes. Java states the rule for hashCode: "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."1 Rust states it as "k1 == k2 -> hash(k1) == hash(k2)".2

The rule is one part of a contract. Equality must also be an equivalence relation: reflexive, symmetric and transitive. The hash code must not change while the object is in a table. A type that breaks any part of the contract compiles and runs, but a hash set can then hold duplicates, or lose an object that it holds.

How it works

The contract has these parts. The words come from Java's Object, and the other languages state the same rules.1

Part Rule What breaks without it
Reflexive x.equals(x) is true a lookup cannot find the key that went in
Symmetric x.equals(y) if and only if y.equals(x) the answer depends on which object the table holds
Transitive x equals y and y equals z, so x equals z a set keeps different items for each insertion order
Consistent the result does not change while the fields do not change a key found once is not found again
Not null x.equals(null) is false code that compares an object with null throws an exception
Hash agrees equal objects give equal hash codes equal keys go to different buckets, and the set keeps both
Hash stable the hash code does not change while the fields that equality reads do not change the table looks in the wrong bucket

The rule goes in one direction only. Java says: "It is not required that if two objects are unequal according to the equals method, then calling the hashCode method on each of the two objects must produce distinct integer results."1 .NET says the same: "equal hash codes do not imply object equality, because different (unequal) objects can have identical hash codes."3 Two unequal keys with the same hash code are a collision. A collision makes the table slower, because equality must compare more keys, but the result stays correct. A hash code that is the same constant for every object keeps the contract and makes every lookup a linear search.

The simplest way to keep the contract is to compute the hash from the same fields that equality compares, and from no others. Python advises this: "The only required property is that objects which compare equal have the same hash value; it is advised to mix together the hash values of the components of the object that also play a part in comparison of objects".4 If equality ignores a difference, such as the case of a string, the hash must ignore it too, usually by hashing a normalized form.

In languages

LanguageVerdictNote
PythonNative
C++Standard library
JavaNative
CAbsentThe C standard library has no hash table; a library hash table takes a hash function and an equality function from the caller.
C#Native
JavaScriptAbsent
TypeScriptAbsentAs JavaScript; Map and Set compare object keys by identity, and the types add no hash hook; no example file because it would repeat the JavaScript answer.
GoNative
RustStandard library
KotlinNativeAny declares equals and hashCode, and a data class generates both from the same properties; no example file because kotlinc is not installed on the machine that recorded the examples.
SQLDoes not applySQL compares and hashes column values; rows have no user methods.
BashDoes not applyBash associative arrays have string keys only, and strings compare by value.
PowerShellNativePowerShell objects are .NET objects, and hashtables call their Equals and GetHashCode methods; no example file because it would repeat the C# answer.
HTMLDoes not applyHTML has no objects with equality.
CSSDoes not applyCSS has no objects with equality.
Regular expressionsDoes not applyRegular expressions have no objects.
Language Verdict Mechanism
Python native __eq__ and __hash__; a class that defines only __eq__ gets __hash__ = None
JavaScript absent Map and Set use SameValueZero, which is identity for objects; no user hash
TypeScript absent as JavaScript
Java native equals and hashCode on Object, with the contract in their documentation
Kotlin native equals and hashCode on Any; a data class generates both
C# native Equals and GetHashCode on Object; IEqualityComparer<T> gives a separate pair
Go native map keys use the built-in == and hash of a comparable type; no user hash
Rust stdlib traits PartialEq, Eq and Hash; HashMap needs Eq + Hash
C absent no hash tables in the standard library; a library takes a hash function and an equality function
C++ stdlib std::unordered_set takes a hash type and an equality type; std::hash and operator== by default
Bash n/a associative arrays have string keys only
PowerShell native .NET objects with Equals and GetHashCode; hashtables use them
SQL n/a a database compares and hashes column values; no user types with methods
Regex n/a no objects
HTML n/a no objects
CSS n/a no objects
  • Java, Kotlin and C# put the two methods on the root class, so each override of one needs an override of the other. Kotlin says: "When overriding the equals() function, you should also override the hashCode() function to keep consistency between equality and hashing".5 .NET says that derived classes that override one method "must also override Equals(Object) to guarantee that two objects considered equal have the same hash code".3
  • Python enforces half of the rule. "A class that overrides eq() and does not define hash() will have its hash() implicitly set to None", so its objects cannot go into a set.4 A @dataclass with eq=True and frozen=True generates a hash; with eq=True and no frozen, "hash() will be set to None, marking it unhashable (which it is, since it is mutable)."6
  • Rust makes the contract part of the types. HashSet<T> needs T: Eq + Hash, and #[derive(PartialEq, Eq, Hash)] uses the same fields for both. The compiler cannot check that a hand-written Hash agrees with a hand-written PartialEq; the documentation calls a mismatch a logic error.
  • Go does not let code define equality or hashing for map keys. The key type must be comparable: "The comparison operators == and != must be fully defined for operands of the key type; thus the key type must not be a function, map, or slice."7 The built-in hash always agrees with the built-in ==.
  • JavaScript has no hook. MDN says that "JavaScript does not provide a general deep comparison operator",8 and a Map with object keys compares references. Code that needs value keys builds a string or a number from the fields.
PythonGitHub
from dataclasses import dataclass


class Tag:
    def __init__(self, name):
        self.name = name

    def __eq__(self, other):
        return isinstance(other, Tag) and self.name == other.name


print(Tag.__hash__)
try:
    {Tag("x")}
except TypeError as e:
    print("TypeError:", e)


@dataclass(frozen=True)
class FrozenTag:
    name: str


s = {FrozenTag("x"), FrozenTag("x")}
print(len(s), hash(FrozenTag("x")) == hash(FrozenTag("x")))
Output
None
TypeError: unhashable type: 'Tag'
1 True
  • Verdict: native. A class that defines __eq__ and not __hash__ gets __hash__ set to None, so Python refuses to put it in a set instead of letting it break the set.
  • @dataclass(frozen=True) generates __eq__ and __hash__ from the same fields, and the frozen fields cannot change after the object goes into a set.
  • A plain @dataclass with eq=True and no frozen also sets __hash__ to None, because its fields can change.
#include <cstddef>
#include <functional>
#include <iostream>
#include <string>
#include <unordered_set>

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

// The hash reads the same members that operator== compares.
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));
    }
};

int main() {
    std::unordered_set<Point, PointHash> s{{1, 2}, {1, 2}, {2, 1}};
    std::cout << s.size() << ' ' << s.count({1, 2}) << ' ' << s.count({3, 3}) << '\n';
}
Output
2 1 0
  • Verdict: stdlib. std::unordered_set takes a hash type and an equality type as template parameters; the defaults are std::hash<T> and std::equal_to<T>, which calls operator==.
  • The standard library has no std::hash for a user type, so the code gives one. It mixes the same two members that the defaulted operator== compares.
  • A hash that reads a member that operator== ignores lets equal points go to different buckets, and the set then keeps duplicates.
JavaGitHub
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

public class Main {
    static final class NoHash {
        final String id;
        NoHash(String id) { this.id = id; }

        @Override
        public boolean equals(Object o) {
            return o instanceof NoHash n && id.equals(n.id);
        }
    }

    static final class WithHash {
        final String id;
        WithHash(String id) { this.id = id; }

        @Override
        public boolean equals(Object o) {
            return o instanceof WithHash w && id.equals(w.id);
        }

        @Override
        public int hashCode() {
            return Objects.hash(id);
        }
    }

    public static void main(String[] args) {
        Set<NoHash> a = new HashSet<>();
        a.add(new NoHash("x"));
        System.out.println(new NoHash("x").equals(new NoHash("x")) + " " + a.contains(new NoHash("x")));

        Set<WithHash> b = new HashSet<>();
        b.add(new WithHash("x"));
        b.add(new WithHash("x"));
        System.out.println(b.contains(new WithHash("x")) + " " + b.size());
    }
}
Output
true false
true 1
  • Verdict: native. Object gives equals and hashCode, and the contract of hashCode says that equal objects must produce the same integer.
  • NoHash breaks the contract: two equal objects keep the identity hash of Object, so HashSet.contains looks in the wrong bucket and returns false.
  • WithHash hashes the same field that equals compares, and the set keeps one copy.
using System;
using System.Collections.Generic;

var set = new HashSet<Sku> { new("A-1"), new("a-1") };
Console.WriteLine($"{set.Count} {set.Contains(new Sku("A-1"))}");

var cmp = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "A-1", "a-1" };
Console.WriteLine(cmp.Count);

// Equality and hash both ignore case, so equal values share a bucket.
sealed class Sku : IEquatable<Sku>
{
    public Sku(string code) => Code = code;

    public string Code { get; }

    public bool Equals(Sku? other) =>
        other is not null && StringComparer.OrdinalIgnoreCase.Equals(Code, other.Code);

    public override bool Equals(object? obj) => Equals(obj as Sku);

    public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Code);
}
Output
1 True
1
  • Verdict: native. Object declares Equals and GetHashCode, and a class that overrides one of them must override the other, so that equal objects have the same hash code.
  • Sku uses one comparer, StringComparer.OrdinalIgnoreCase, for both the equality and the hash, so they cannot disagree.
  • A collection can also take an IEqualityComparer<T>, which gives a second pair of equality and hash without a change to the type.
JavaScriptGitHub
const m = new Map();
m.set({ x: 1 }, "first");
m.set({ x: 1 }, "second");
console.log(m.size, m.get({ x: 1 }));

const byKey = new Map();
for (const p of [{ x: 1 }, { x: 1 }, { x: 2 }]) {
  byKey.set(JSON.stringify(p), p);
}
console.log(byKey.size, byKey.has(JSON.stringify({ x: 1 })));

const nums = new Set([NaN, NaN, 0, -0]);
console.log(nums.size, NaN === NaN);
Output
2 undefined
2 true
2 false
  • Verdict: absent. A Map or Set compares keys with SameValueZero, which for objects is identity, and code cannot give a class its own equality or hash.
  • Two objects with the same fields are two keys. The usual work-around is a key of a primitive type, such as a string built from the fields; JSON.stringify works here only because the property order is the same.
  • SameValueZero treats NaN as equal to NaN and -0 as equal to 0, so the set of numbers has 2 items although NaN === NaN is false.
package main

import (
	"fmt"
	"math"
)

type Point struct{ X, Y float64 }

func main() {
	m := map[Point]int{}
	m[Point{1, 2}]++
	m[Point{1, 2}]++
	fmt.Println(len(m), m[Point{1, 2}])

	nan := math.NaN()
	m[Point{nan, 0}]++
	m[Point{nan, 0}]++
	fmt.Println(len(m), m[Point{nan, 0}])

	var keys = map[any]bool{}
	defer func() { fmt.Println("panic:", recover()) }()
	keys[[]int{1}] = true
}
Output
1 2
3 0
panic: runtime error: hash of unhashable type []int
  • Verdict: native. Go has no user hash: a map key must be comparable, and the map uses the built-in == and the built-in hash of the key type, so they always agree.
  • A float field breaks reflexivity: NaN != NaN, so each Point{NaN, 0} is a new key that a lookup cannot find.
  • A key of interface type is checked at run time. A slice is not comparable, so storing one as a key of map[any]bool panics.
RustGitHub
use std::collections::HashSet;
use std::hash::{Hash, Hasher};

// A tag whose equality ignores case.
#[derive(Debug)]
struct Tag(String);

impl PartialEq for Tag {
    fn eq(&self, other: &Self) -> bool {
        self.0.eq_ignore_ascii_case(&other.0)
    }
}

impl Eq for Tag {}

// The hash must ignore case too, or equal tags land in different buckets.
impl Hash for Tag {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.0.to_ascii_lowercase().hash(state);
    }
}

fn main() {
    let mut tags = HashSet::new();
    tags.insert(Tag("Rust".to_string()));
    tags.insert(Tag("RUST".to_string()));
    tags.insert(Tag("rust".to_string()));
    println!("{} {}", tags.len(), tags.contains(&Tag("rUsT".to_string())));

    let x = f64::NAN;
    println!("{} {}", x == x, x.partial_cmp(&x).is_none());
}
Output
1 true
false true
  • Verdict: stdlib. Eq and Hash are traits, and HashSet and HashMap need both. A hand-written PartialEq that ignores case needs a Hash that ignores case too.
  • The compiler does not check that the two traits agree; a Hash that reads the original string would compile and give a set with 3 tags.
  • f64 implements PartialEq and not Eq, because NaN is not equal to itself, so HashSet<f64> does not compile.
  • A separate comparer. C#'s IEqualityComparer<T> and the hash and equality template parameters of C++'s std::unordered_set let a collection use an equality and a hash that the type does not define. The two still must agree.
  • Partial equality. IEEE 754 floating-point numbers break reflexivity, because NaN is not equal to itself. Rust records this in the types: "Floating point types such as f32 and f64 implement only PartialEq but not Eq because NaN != NaN."9 Rust's PartialEq exists "for types that do not have a full equivalence relation."10
  • Identity equality. The default equals and hash code of a Java or C# object use identity, which keeps the contract trivially. A type needs the contract only when it changes equality to compare values. See value equality and identity.
  • Ordering. A sorted map such as Java's TreeMap uses compareTo in place of equals and hashCode. The ordering should be consistent with equality, which is part of natural ordering.

Pitfalls

  • Override one and not the other. In Java, a class that overrides equals and keeps the identity hash code of Object gives false for set.contains(copy), although copy.equals(original) is true. Java's note: "It is generally necessary to override the hashCode method whenever this method is overridden".1
  • A mutable key. If a field that the hash reads changes after the object goes into a hash set, the object stays in the bucket of its old hash code:
class Key:
    def __init__(self, name):
        self.name = name

    def __eq__(self, other):
        return isinstance(other, Key) and self.name == other.name

    def __hash__(self):
        return hash(self.name)


k = Key("a")
s = {k}
print(Key("a") in s)
k.name = "b"
print(k in s, Key("b") in s, len(s))
Output
True
False False 1

The set still holds one object, but no lookup finds it. Python's advice is that a class that "defines mutable objects and implements an eq() method, it should not implement hash()".4 Use immutable fields for keys, or take the object out of the set before the change.

  • A hash that reads more than equality. If equality ignores the case of a string and the hash does not, "Rust" and "RUST" are equal but go to different buckets. Hash the normalized form that equality compares.
  • Equality across subclasses. If a subclass adds a field to equals, equality is not symmetric any more, and the hash codes of the base and the subclass can differ for objects that one side calls equal. Implement equality for a type shows the case with a run block.
  • Floating-point fields. A key with a NaN field is not equal to itself, so a Go map or a hand-written equality can store it many times and never find it again.
  • Hash codes that persist. .NET does not guarantee the default hash code, and the value "might differ between .NET implementations and platforms".3 Java says that the hash code "need not remain consistent from one execution of an application to another".1 Do not store hash codes in files or send them over a network.

Cost

Equality and hashing should cost about the same: each reads the fields that define the value once. A lookup in a hash table computes the hash of the key once, then calls equality on each key in the bucket with the same hash code, so a good hash keeps the number of equality calls near one. A bad hash, which puts many keys in one bucket, makes each lookup grow with the number of keys. An immutable type with large fields, such as long strings or lists, can compute its hash code once and keep it.

History

JDK 1.0, released on January 23, 1996,11 put equals and hashCode on java.lang.Object, and the documentation of hashCode states the contract that later languages copied. Python's data model and .NET's GetHashCode state the same rule. Later languages moved the rule closer to the compiler: Rust's HashMap needs both Eq and Hash, and derive generates both from the same fields.

References

  1. Object (Java SE 21 & JDK 21), API documentation, equals; hashCode
  2. Hash trait, Rust standard library, Hash and Eq
  3. Object.GetHashCode Method, .NET API reference, Remarks; Notes to Inheritors
  4. Data model, The Python Language Reference, 3.3.1 Basic customization, object.__hash__
  5. Equality, Kotlin documentation, Structural equality
  6. dataclasses, Python standard library, Module contents, unsafe_hash
  7. The Go Programming Language Specification, Map types
  8. Equality comparisons and sameness, MDN, Same-value-zero equality
  9. Eq trait, Rust standard library, Description
  10. PartialEq trait, Rust standard library, Description
  11. Java version history, Wikipedia, Release table

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/X2FZ6P/text.yaml