M04 · Built-in Collections

Iterators, Equality and Hashing Contracts

A collection relies on promises from the code that uses it. Iterators assume you do not change the collection under them. Hash maps assume equal keys have equal hashes and never change. Sorted collections assume a consistent ordering. Break a promise and the result is an exception at best and a silently lost element at worst. This lesson lists the promises and how each language enforces them.

~35 minBeginnerC# · Python · Java · C++
Curriculum: M04 Built-in Collections · 3 of 3 lessons available

You will be able to

  • Explain what an iterator is in each language and what a traversal costs, including iteration over a hash table.
  • Predict what happens when a collection is modified during iteration in C#, Python, Java and C++, and use the safe alternatives.
  • State the equality and hash contract and implement value equality correctly with records, dataclasses or defaulted operators.
  • State what a comparator must satisfy (a strict weak ordering, consistent with equals) and why sorted collections depend on it.
  • Recognise unsafe keys: mutable objects, arrays, floating-point NaN.

Helpful before this lesson

  • M02 Memory Model — What a variable, a reference and a buffer really are, and why contiguous memory is fast.
  • M03 Big O — Count operations, describe growth, and tell worst-case, average and amortized costs apart.

Guidance only. Those modules are planned; the essentials are recapped here.

Visual walkthrough

The interactive visualizer needs JavaScript. The explanation and all four implementations below work without it.

Collections run on contracts

A collection's documented costs assume that the code using it keeps three promises:

  1. Do not change the collection behind an iterator's back, except through the iterator itself.
  2. Keys of hash-based collections: equal keys have equal hashes, and a key's hash and equality do not change while it is stored.
  3. Keys of sorted collections: the comparison is a consistent ordering.

None of the four languages can check all of this. Some violations throw, some are undefined behaviour, and some silently lose data. This lesson goes through each promise.

Iterators

An iterator is an object that remembers a position in a collection and can move to the next element. Every foreach / for … in / range-for loop uses one:

Language Protocol Loop
C# IEnumerable<T>.GetEnumerator() returns an IEnumerator<T> with MoveNext() and Current foreach (var x in items)
Python iter(obj) calls __iter__; next() calls __next__, which raises StopIteration at the end for x in items:
Java Iterable<T>.iterator() returns an Iterator<T> with hasNext(), next() and optional remove() for (var x : items)
C++ a pair of iterators begin() / end(); end is one past the last element (half-open) for (auto& x : items)

C++ classifies iterators by what they can do: input, forward, bidirectional, random access and (since C++20) contiguous. Algorithms state which category they need, which is why std::sort needs random access and std::list has its own sort member.

Traversal cost. Visiting all n elements is Θ(n) for arrays, lists, deques and trees (an in-order walk of a balanced tree is Θ(n) in total). A hash table is the exception worth knowing: a chained table visits its buckets, so a traversal costs time proportional to capacity plus size. Java's HashMap documentation says exactly this, and warns against setting the initial capacity too high if iteration performance matters.

Modifying a collection while iterating

Language What happens
C# List<T>, Dictionary and most BCL collections keep a version number; the next MoveNext() after a modification throws InvalidOperationException. Since .NET Core 3.0, Dictionary.Remove and Clear during enumeration are allowed.
Python Changing the size of a dict or set during iteration raises RuntimeError. A list raises nothing: elements are silently skipped or visited twice.
Java Iterators of the standard collections are fail-fast: they usually throw ConcurrentModificationException, but the documentation stresses this is best-effort, not guaranteed.
C++ No check. Using an invalidated iterator is undefined behaviour. Each container documents which operations invalidate which iterators: a std::vector reallocation invalidates all of them; erase invalidates those at and after the erased position.

Safe alternatives that work in each language:

  • Build a new collection, or collect the changes and apply them after the loop.
  • C#: list.RemoveAll(predicate); iterate a copy (list.ToList()) if you must modify.
  • Python: a comprehension ([x for x in items if keep(x)]); iterate over list(d) to delete dictionary keys.
  • Java: Iterator.remove(), or collection.removeIf(predicate).
  • C++: it = v.erase(it) (erase returns the next valid iterator), or std::erase_if(container, predicate) since C++20.

Equality: identity or value?

Two objects can be the same object (identity) or equal (same value). Collections use equality for Contains, indexOf, in, and to find keys. The defaults differ:

Language Default for your own class Value equality without boilerplate
C# classes: reference equality; structs: field by field (ValueType.Equals, often via reflection; override it for speed) record / record struct generate Equals, GetHashCode and ==
Python identity (__eq__ inherited from object) @dataclass generates __eq__; with frozen=True also __hash__
Java identity (Object.equals) record generates equals, hashCode and toString
C++ no == at all unless you declare one bool operator==(const T&) const = default; (C++20)

Java's == on objects always compares references; use equals. In Python, membership tests on the built-in containers check x is e or x == e, identity first, which matters for the NaN case below.

The hash contract

A hash map finds a key by computing its hash, going to that bucket, and then comparing keys with equality. That only works if:

  1. Equal keys have equal hashes. If a.Equals(b) then a.GetHashCode() == b.GetHashCode() (and likewise __eq__/__hash__, equals/hashCode, ==/the hasher). The converse is not required: different keys may share a hash; that is a collision.
  2. The hash does not change while the key is in the table. Mutating a field that participates in the hash strands the entry in its old bucket.
  3. For speed, not correctness: hashes should spread keys evenly.

The lab above shows rule 3 failing gracefully: in the Collisions preset keys 1, 5 and 9 share a bucket, so lookups walk a chain and the Key comparisons metric grows. A constant hash (every key in one bucket) is legal and turns every operation into a linear scan. The hash table lesson covers buckets, load factor and the contract in each language.

How each language enforces rule 1:

  • C#: overriding Equals without GetHashCode produces a compiler warning. Records do both.
  • Python: defining __eq__ without __hash__ sets __hash__ to None, so the class becomes unhashable: a loud failure instead of a silent one. A non-frozen @dataclass with eq=True does the same.
  • Java: nothing stops you; HashMap then fails silently. Override both, or use a record.
  • C++: std::unordered_map<Key, T> needs a hash. std::hash is specialized for built-in types, strings and smart pointers, but not for std::pair, std::tuple or std::vector<int>; you must supply a hasher. Ordered std::map only needs operator<.

Keys to avoid

Key Problem Instead
A mutable object whose fields feed its hash entry becomes unfindable after mutation immutable keys: strings, tuples, records, frozen dataclasses
Arrays (int[] in C# and Java) equality and hash are by reference, so two equal arrays are different keys C# a record or a string; Java List.of(...) or a record; Python a tuple (lists are unhashable)
Floating-point NaN NaN == NaN is false avoid as a key; see below

NaN as a key. C#'s double.Equals and Java's Double.equals deliberately treat NaN as equal to itself, so HashSet<double> / HashSet<Double> can find it even though == says otherwise. C++ std::unordered_set<double> uses ==: every inserted NaN is a new element and find never finds one. Python finds the same NaN object (identity is checked first) but not a different NaN object. Four languages, three behaviours: keep NaN out of keys.

Ordering contracts for sorted collections and sorting

Sorted collections and sort functions compare keys instead of hashing them. The comparison must be a strict weak ordering: never a < a; if a < b then not b < a; transitive; and "equivalent" (neither is less) must itself be transitive. Violations cause wrong results, and in C++ undefined behaviour (including out-of-bounds reads in some sort implementations).

  • C++: std::map and std::set treat a and b as the same key when !comp(a, b) && !comp(b, a). operator== is never called.
  • Java: TreeMap and TreeSet use compareTo or the Comparator, not equals. If the ordering is not consistent with equals, the set breaks the Set contract. The Comparable documentation's example is BigDecimal: 4.0 and 4.00 are not equals, but compareTo returns 0, so a TreeSet keeps only one of them while a HashSet keeps both.
  • C#: SortedSet<T> and SortedDictionary use IComparer<T>; a comparer that returns 0 makes two elements duplicates: SortedSet<T>.Add returns false for the second, and SortedDictionary.Add throws ArgumentException.
  • Python: there is no comparator argument; sorting and bisect take a key= function, and functools.cmp_to_key adapts an old-style comparison. Keys must be mutually comparable with <; mixing incomparable types raises TypeError.

A classic comparator bug: (a, b) -> a - b in Java or C#. For large values the subtraction overflows and flips the sign. Use Integer.compare(a, b) / a.CompareTo(b).

Common mistakes

  • Removing from a list inside a foreach / for-each loop.
  • Overriding equality without the hash (Java), or using mutable objects as keys.
  • Using arrays as dictionary keys in C# or Java and wondering why lookups miss.
  • Writing a comparator that is not a strict weak ordering (<= instead of < in C++), or one that subtracts.
  • Assuming a TreeSet/SortedSet uses equals: it uses the comparison.
  • Relying on hash map iteration order, which can change after a resize.

Worked practice

1. A Java class overrides equals but not hashCode. You add an object to a HashSet and then call contains with an equal but different object. Result?

Almost certainly false. The default hashCode is identity-based, so the second object hashes to a different bucket and equals is never even called. Override both, or make it a record.

2. In Python, d = {}; for k in d: if bad(k): del d[k]. What happens, and how do you fix it?

RuntimeError: dictionary changed size during iteration as soon as a key is deleted. Iterate over a snapshot, for k in list(d):, or rebuild: d = {k: v for k, v in d.items() if not bad(k)}.

3. Why does a C++ std::set with comparator [](int a, int b) { return a <= b; } misbehave?

<= is not a strict weak ordering: comp(a, a) is true. The set can no longer recognise equivalent elements (!comp(a, b) && !comp(b, a) is never true for equal values), so duplicates get inserted and find fails. Formally, the behaviour is undefined.

4. Iterating a HashMap with 10 entries is unexpectedly slow. What might be the cause?

A huge initial capacity (or a map that once held millions of entries and was cleared). Iteration time is proportional to capacity plus size, so 10 entries in 10 million buckets still visits every bucket. Create the map with a sensible capacity, or copy it into a new one.

Summary

  • Iterators assume the collection does not change under them: C# and Java usually throw, Python throws for dicts and sets, C++ gives undefined behaviour.
  • Equal keys must have equal hashes, and a stored key must not change. Records, dataclasses and defaulted operators get this right for you.
  • Sorted collections use the comparison, not equality, and the comparison must be a strict weak ordering.
  • Keep arrays, mutable objects and NaN out of keys.
  • A hash table traversal costs capacity plus size, not just size.

Full implementation

The chained hash table in four languages, checked against one shared fixture of put, get and remove sequences, including collisions, overwrites and resizing.

namespace Bekadan.Dsa.Examples.Hashing;
 
/// <summary>
/// A teaching hash table with separate chaining. bucket = floorMod(key, capacity),
/// initial capacity 4, doubling before an insert would push the load factor
/// above 0.75. Dictionary&lt;TKey, TValue&gt; uses other details; the costs are the same.
/// </summary>
public sealed class ChainedHashTable
{
    private List<(int Key, int Value)>[] _buckets = NewBuckets(4);
 
    public int Count { get; private set; }
 
    public int Capacity => _buckets.Length;
 
    private static List<(int Key, int Value)>[] NewBuckets(int capacity)
    {
        var buckets = new List<(int Key, int Value)>[capacity];
        for (int b = 0; b < capacity; b++)
            buckets[b] = [];
        return buckets;
    }
 
    private static int BucketOf(int key, int capacity) => ((key % capacity) + capacity) % capacity;
 
    public void Put(int key, int value)
    {
        var chain = _buckets[BucketOf(key, _buckets.Length)];
        for (int i = 0; i < chain.Count; i++)
        {
            if (chain[i].Key == key)
            {
                chain[i] = (key, value);
                return;
            }
        }
        if (4 * (Count + 1) > 3 * _buckets.Length) // (Count + 1) / capacity > 0.75, in integers
            Resize();
        _buckets[BucketOf(key, _buckets.Length)].Add((key, value));
        Count++;
    }
 
    private void Resize()
    {
        var next = NewBuckets(_buckets.Length * 2);
        foreach (var chain in _buckets)
            foreach (var entry in chain)
                next[BucketOf(entry.Key, next.Length)].Add(entry);
        _buckets = next;
    }
 
    public bool TryGet(int key, out int value)
    {
        var chain = _buckets[BucketOf(key, _buckets.Length)];
        foreach (var entry in chain)
        {
            if (entry.Key == key)
            {
                value = entry.Value;
                return true;
            }
        }
        value = 0;
        return false;
    }
 
    public bool Remove(int key, out int value)
    {
        var chain = _buckets[BucketOf(key, _buckets.Length)];
        for (int i = 0; i < chain.Count; i++)
        {
            if (chain[i].Key == key)
            {
                value = chain[i].Value;
                chain.RemoveAt(i);
                Count--;
                return true;
            }
        }
        value = 0;
        return false;
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Hashing/ChainedHashTable.cs

"""A teaching hash table with separate chaining.
 
bucket = key mod capacity (Python's % already floors for negative keys),
initial capacity 4, doubling before an insert would push the load factor
above 0.75. CPython's dict uses open addressing instead; the costs are the same.
"""
 
 
class ChainedHashTable:
    def __init__(self) -> None:
        self._buckets: list[list[tuple[int, int]]] = [[] for _ in range(4)]
        self._count = 0
 
    def __len__(self) -> int:
        return self._count
 
    @property
    def capacity(self) -> int:
        return len(self._buckets)
 
    def put(self, key: int, value: int) -> None:
        chain = self._buckets[key % len(self._buckets)]
        for i, (existing, _) in enumerate(chain):
            if existing == key:
                chain[i] = (key, value)
                return
        if 4 * (self._count + 1) > 3 * len(self._buckets):  # (count + 1) / capacity > 0.75, in integers
            self._resize()
        self._buckets[key % len(self._buckets)].append((key, value))
        self._count += 1
 
    def _resize(self) -> None:
        new_buckets: list[list[tuple[int, int]]] = [[] for _ in range(2 * len(self._buckets))]
        for chain in self._buckets:
            for entry in chain:
                new_buckets[entry[0] % len(new_buckets)].append(entry)
        self._buckets = new_buckets
 
    def get(self, key: int) -> int | None:
        chain = self._buckets[key % len(self._buckets)]
        for existing, value in chain:
            if existing == key:
                return value
        return None
 
    def remove(self, key: int) -> int | None:
        chain = self._buckets[key % len(self._buckets)]
        for i, (existing, value) in enumerate(chain):
            if existing == key:
                del chain[i]
                self._count -= 1
                return value
        return None

Tested on CPython 3.14.0 · examples/python/dsa_examples/hash_table.py

package dev.bekadan.dsa.hashing;
 
import java.util.ArrayList;
import java.util.List;
import java.util.OptionalInt;
 
/**
 * A teaching hash table with separate chaining. bucket = Math.floorMod(key, capacity),
 * initial capacity 4, doubling before an insert would push the load factor above
 * 0.75. HashMap uses other details (power-of-two tables, tree bins); the costs are the same.
 */
public final class ChainedHashTable {
    private record Entry(int key, int value) {
    }
 
    private List<List<Entry>> buckets = newBuckets(4);
    private int count;
 
    private static List<List<Entry>> newBuckets(int capacity) {
        List<List<Entry>> result = new ArrayList<>(capacity);
        for (int b = 0; b < capacity; b++) {
            result.add(new ArrayList<>());
        }
        return result;
    }
 
    public int size() {
        return count;
    }
 
    public int capacity() {
        return buckets.size();
    }
 
    public void put(int key, int value) {
        List<Entry> chain = buckets.get(Math.floorMod(key, buckets.size()));
        for (int i = 0; i < chain.size(); i++) {
            if (chain.get(i).key() == key) {
                chain.set(i, new Entry(key, value));
                return;
            }
        }
        if (4 * (count + 1) > 3 * buckets.size()) { // (count + 1) / capacity > 0.75, in integers
            resize();
        }
        buckets.get(Math.floorMod(key, buckets.size())).add(new Entry(key, value));
        count++;
    }
 
    private void resize() {
        List<List<Entry>> next = newBuckets(buckets.size() * 2);
        for (List<Entry> chain : buckets) {
            for (Entry entry : chain) {
                next.get(Math.floorMod(entry.key(), next.size())).add(entry);
            }
        }
        buckets = next;
    }
 
    public OptionalInt get(int key) {
        List<Entry> chain = buckets.get(Math.floorMod(key, buckets.size()));
        for (Entry entry : chain) {
            if (entry.key() == key) {
                return OptionalInt.of(entry.value());
            }
        }
        return OptionalInt.empty();
    }
 
    public OptionalInt remove(int key) {
        List<Entry> chain = buckets.get(Math.floorMod(key, buckets.size()));
        for (int i = 0; i < chain.size(); i++) {
            if (chain.get(i).key() == key) {
                int value = chain.remove(i).value();
                count--;
                return OptionalInt.of(value);
            }
        }
        return OptionalInt.empty();
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/hashing/ChainedHashTable.java

#pragma once
 
#include <cstddef>
#include <optional>
#include <utility>
#include <vector>
 
namespace bekadan::dsa {
 
// A teaching hash table with separate chaining. bucket = floorMod(key, capacity),
// initial capacity 4, doubling before an insert would push the load factor above
// 0.75. std::unordered_map uses other details (max_load_factor 1.0 by default).
class ChainedHashTable {
    using Entry = std::pair<int, int>;  // key, value
    using Chain = std::vector<Entry>;
 
public:
    [[nodiscard]] std::size_t size() const noexcept { return count_; }
    [[nodiscard]] std::size_t capacity() const noexcept { return buckets_.size(); }
 
    void put(int key, int value) {
        Chain& chain = buckets_[bucket_of(key, buckets_.size())];
        for (Entry& entry : chain) {
            if (entry.first == key) {
                entry.second = value;
                return;
            }
        }
        if (4 * (count_ + 1) > 3 * buckets_.size())  // (count + 1) / capacity > 0.75, in integers
            resize();  // `chain` may dangle after this: look the bucket up again
        buckets_[bucket_of(key, buckets_.size())].emplace_back(key, value);
        ++count_;
    }
 
    [[nodiscard]] std::optional<int> get(int key) const {
        const Chain& chain = buckets_[bucket_of(key, buckets_.size())];
        for (const Entry& entry : chain) {
            if (entry.first == key)
                return entry.second;
        }
        return std::nullopt;
    }
 
    std::optional<int> remove(int key) {
        Chain& chain = buckets_[bucket_of(key, buckets_.size())];
        for (std::size_t i = 0; i < chain.size(); ++i) {
            if (chain[i].first == key) {
                int value = chain[i].second;
                chain.erase(chain.begin() + static_cast<std::ptrdiff_t>(i));
                --count_;
                return value;
            }
        }
        return std::nullopt;
    }
 
private:
    static std::size_t bucket_of(int key, std::size_t capacity) {
        const auto c = static_cast<long long>(capacity);
        return static_cast<std::size_t>(((key % c) + c) % c);
    }
 
    void resize() {
        std::vector<Chain> next(buckets_.size() * 2);
        for (const Chain& chain : buckets_)
            for (const Entry& entry : chain) next[bucket_of(entry.first, next.size())].push_back(entry);
        buckets_ = std::move(next);
    }
 
    std::vector<Chain> buckets_ = std::vector<Chain>(4);
    std::size_t count_ = 0;
};
 
}  // namespace bekadan::dsa

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/chained_hash_table.hpp

References