Sub topic 12
Equality and hashCode: Custom Objects in Sets and Map Keys
This chapter assumes you can write Dart classes with final fields and constructors, and that you know how Set and Map literals behave from the earlier chapters. Here you will learn how Set and Map decide that two objects are "the same". You will also see how to make your own classes work correctly as set elements and map keys, and how the usual mistakes show up.
How sets and maps compare elements
A set literal such as {1, 2, 3} creates a LinkedHashSet. A map literal creates a LinkedHashMap. Both are hash-based. When you add an element or look up a key, Dart does not compare it against every stored element. It runs these steps:
- It calls
hashCodeon the key. This returns anint. - It looks only at stored keys whose hash matches.
- Among those candidates, it uses
==to find an exact match.
Both steps must agree. If two objects are equal but have different hash codes, the lookup may never reach the stored object. If two objects have the same hash code but are not ==, they are simply different keys. That is a collision, and it is harmless.
Default equality is identity
A class that does not override == inherits the version from Object. That version returns true only when both references point to the same object. Two instances with identical field values are different keys.
class Tag {
final String name;
Tag(this.name);
}
void main() {
final tags = {Tag('dart'), Tag('dart')};
print(tags.length); // 2, two distinct objects
final one = Tag('flutter');
final more = {one, one};
print(more.length); // 1, same object twice
}Built-in value types such as int, String, and bool already compare by value, so {'a', 'a'} holds one element. Lists, maps, and sets do not compare by value. [1, 2] == [1, 2] is false.
Overriding == and hashCode together
To make a class behave as a value, override both members. They must follow one rule: if a == b, then a.hashCode == b.hashCode. The reverse need not hold.
class Point {
final int x;
final int y;
const Point(this.x, this.y);
@override
bool operator ==(Object other) =>
other is Point && other.x == x && other.y == y;
@override
int get hashCode => Object.hash(x, y);
}
void main() {
final seen = <Point>{};
print(seen.add(const Point(1, 2))); // true
print(seen.add(Point(1, 2))); // false, equal to the stored point
final labels = <Point, String>{Point(0, 0): 'origin'};
print(labels[Point(0, 0)]); // origin
print(labels[Point(9, 9)]); // null
}Object.hash combines up to twenty values into one well-mixed hash. For a variable number of values, such as a list field, use Object.hashAll(iterable). Avoid hand-rolled formulas like x + y. With that formula Point(1, 2) and Point(2, 1) collide, which slows lookups.
A few details of a correct ==:
- Take an
Objectparameter and test it withis. Do not cast. - Compare every field that you include in
hashCode. Leave out any field that is not part of the object's identity. other is Pointalso accepts subclasses. If a subclass adds fields,==can become asymmetric (a == bbutb != a). Either make the classfinal, or compareruntimeTypeas well.
Common errors
Overriding only ==
If you override == but not hashCode, the inherited identity hash is used. Equal objects then have different hashes, so the set rarely gets to the == check.
class Broken {
final int id;
Broken(this.id);
@override
bool operator ==(Object other) => other is Broken && other.id == id;
// hashCode not overridden: this violates the contract
}
void main() {
final s = {Broken(1), Broken(1)};
print(s.length); // almost always 2, but not guaranteed
}The result is unreliable, which makes the bug hard to find. The unnecessary_overrides and hash_and_equals lints in package:lints flag this pair. Turn them on.
Changing a key after inserting it
A set stores an element under the hash it had when it was added. If a field that feeds hashCode changes afterwards, the element sits in the wrong place.
class Box {
int value;
Box(this.value);
@override
bool operator ==(Object other) => other is Box && other.value == value;
@override
int get hashCode => value.hashCode;
}
void main() {
final box = Box(1);
final boxes = {box};
box.value = 2;
print(boxes.contains(box)); // normally false
print(boxes.contains(Box(1))); // false, the hash matches but == fails
print(boxes.length); // 1, the element is still stored
}The element is still stored, but you can no longer reliably find it or remove it. Make fields that feed hashCode final. If you must change such a field, remove the object first and add it again afterwards.
Using a list as a key
Lists use identity equality, so a list key matches only the very same list object.
void main() {
final byRoute = <List<int>, String>{[1, 2]: 'first'};
print(byRoute[[1, 2]]); // null, a different list object
}Dart 3 records offer a simple fix when the parts are values. A record compares structurally, and its hash comes from its fields.
void main() {
final byCell = <(int, int), String>{(1, 2): 'first'};
print(byCell[(1, 2)]); // first
print({(1, 'a'), (1, 'a')}.length); // 1
}The record compares each field with that field's own ==. A record that contains a list therefore still compares the list by identity.
Custom equality without changing the class
Sometimes you cannot edit the class, or you need a different rule for one collection. HashSet and HashMap from dart:collection accept equals and hashCode callbacks. A case-insensitive set of names is an example.
import 'dart:collection';
void main() {
final names = HashSet<String>(
equals: (a, b) => a.toLowerCase() == b.toLowerCase(),
hashCode: (s) => s.toLowerCase().hashCode,
);
print(names.add('Ada')); // true
print(names.add('ADA')); // false, same name ignoring case
print(names.length); // 1
}The two callbacks must satisfy the same contract as == and hashCode. Both here use toLowerCase(), so equal names always hash alike. A HashSet does not promise iteration order. If you need insertion order, use a literal or LinkedHashSet, which accepts the same two parameters.
For structural list comparison, package:collection provides ListEquality, SetEquality, and DeepCollectionEquality. Each has equals and hash methods. You can pass them as the two callbacks to build a map keyed by lists.
Where equality matters outside hash collections
Not every collection operation uses hashCode. The table shows which members rely on what.
| Operation | Uses `==` | Uses `hashCode` |
|---|---|---|
| `List.contains`, `indexOf`, `remove` | Yes | No |
| `Set.contains`, `add`, `remove` | Yes | Yes |
| `Map` key lookup (`[]`, `containsKey`) | Yes | Yes |
| `Map.containsValue` | Yes, on values | No |
| `SplayTreeSet` and `SplayTreeMap` | No, they use `compare` | No |
The last row matters. SplayTreeSet and SplayTreeMap call a compare function instead. Two elements for which compare returns 0 count as the same element, whatever their == says. If you design the comparison, make it return 0 only for objects you consider equal.
Checklist
- Override
==andhashCodetogether, and compare the same fields in both. - Use
Object.hashorObject.hashAllfor the hash. - Keep key fields
final. Never change a field that affectshashCodewhile the object is in a set or map. - Never use lists, sets, or maps as keys unless you supply custom equality. Prefer records of values.
- Use
HashSetorHashMapwith callbacks when you need a different rule for one collection.
Exercise
A class User has fields id and email. You override == to compare only id. Which fields should feed hashCode, and why?
Show answer
Only id. Equal objects must have equal hash codes. Two users with the same id are equal, so their hashes must match even when their emails differ. Including email in the hash would make equal users hash differently, and a set could then store both.
Exercise
This code prints null. Explain why, and give two ways to make it print ok.
final m = <List<int>, String>{[1, 2]: 'ok'};
print(m[[1, 2]]);
Show answer
List keys compare by identity, and [1, 2] in the lookup is a new list object. Fix 1: use a record key, <(int, int), String>{(1, 2): 'ok'}, and look up with (1, 2). Fix 2: build the map with HashMap<List<int>, String>(equals: const ListEquality<int>().equals, hashCode: const ListEquality<int>().hash) from dart:collection and package:collection. Reusing the same list object also works.
Exercise
You add a mutable object to a set, then change a field used in its hashCode. set.length is still 1, but set.contains(obj) returns false. What happened, and how do you avoid it?
Show answer
The set stored the object under its old hash. After the change, a lookup computes the new hash and searches the wrong place. A lookup with an object matching the old values finds the right hash but fails the == check. Avoid it by making the hashed fields final, or by removing the object before changing it and adding it again afterwards.