Collections run on contracts
A collection's documented costs assume that the code using it keeps three promises:
- Do not change the collection behind an iterator's back, except through the iterator itself.
- Keys of hash-based collections: equal keys have equal hashes, and a key's hash and equality do not change while it is stored.
- 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 overlist(d)to delete dictionary keys. - Java:
Iterator.remove(), orcollection.removeIf(predicate). - C++:
it = v.erase(it)(erase returns the next valid iterator), orstd::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:
- Equal keys have equal hashes. If
a.Equals(b)thena.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. - 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.
- 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
EqualswithoutGetHashCodeproduces a compiler warning. Records do both. - Python: defining
__eq__without__hash__sets__hash__toNone, so the class becomes unhashable: a loud failure instead of a silent one. A non-frozen@dataclasswitheq=Truedoes the same. - Java: nothing stops you;
HashMapthen fails silently. Override both, or use a record. - C++:
std::unordered_map<Key, T>needs a hash.std::hashis specialized for built-in types, strings and smart pointers, but not forstd::pair,std::tupleorstd::vector<int>; you must supply a hasher. Orderedstd::maponly needsoperator<.
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::mapandstd::settreataandbas the same key when!comp(a, b) && !comp(b, a).operator==is never called. - Java:
TreeMapandTreeSetusecompareToor theComparator, notequals. If the ordering is not consistent with equals, the set breaks theSetcontract. TheComparabledocumentation's example isBigDecimal:4.0and4.00are notequals, butcompareToreturns 0, so aTreeSetkeeps only one of them while aHashSetkeeps both. - C#:
SortedSet<T>andSortedDictionaryuseIComparer<T>; a comparer that returns 0 makes two elements duplicates:SortedSet<T>.Addreturnsfalsefor the second, andSortedDictionary.AddthrowsArgumentException. - Python: there is no comparator argument; sorting and
bisecttake akey=function, andfunctools.cmp_to_keyadapts an old-style comparison. Keys must be mutually comparable with<; mixing incomparable types raisesTypeError.
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/SortedSetusesequals: 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.