← → or space · progress saves for Continue on the roadmap
Goal
Treat two objects as “the same value” for logic and collections (Set, Map keys).
Step 1 - Default == is identity
class Box {
final int v;
Box(this.v);
}
void main() {
Box a = Box(1);
Box b = Box(1);
print(a == b);
print(identical(a, b));
}- Without overrides,
==is reference equality: same object only.
Step 2 - Override == and hashCode together
class Box {
final int v;
Box(this.v);
@override
bool operator ==(Object other) {
return other is Box && other.v == v;
}
@override
int get hashCode => Object.hash(v);
}
void main() {
Box a = Box(1);
Box b = Box(1);
print(a == b);
final set = {a, b};
print(set.length);
}- If two values are equal, they must have the same
hashCode. Break that rule andSet/Mapbehave badly.
Step 3 - Why collections care
SetandMapusehashCodefor buckets and==for collisions.- Value objects used as keys should be immutable (or at least not change fields that affect
hashCodeafter insertion).
Good habit
- Use
Object.hash(field1, field2, ...)for combining fields (fromdart:core).
Practice tasks
- Add
==/hashCodetoUserwithnameandage(both part of equality). - Build a
Setof threeUserinstances where two are value-equal;lengthshould be2. - Explain in one sentence why mutating a field that affects
hashCodeafter inserting into aSetis dangerous.