hashCode & == Override
Part of the Object Oriented Programming section of Coddy's Dart journey — lesson 71 of 110.
By default, two objects in Dart are only equal if they're the exact same instance in memory. This means two objects with identical values are still considered different:
class Point {
int x, y;
Point(this.x, this.y);
}
void main() {
var p1 = Point(3, 4);
var p2 = Point(3, 4);
print(p1 == p2); // false - different instances!
}To compare objects by their values, you need to override both the == operator and hashCode. These two must always be overridden together - if two objects are equal, they must have the same hash code:
class Point {
final int x, y;
Point(this.x, this.y);
@override
bool operator ==(Object other) {
if (other is! Point) return false;
return x == other.x && y == other.y;
}
@override
int get hashCode => Object.hash(x, y);
}
void main() {
var p1 = Point(3, 4);
var p2 = Point(3, 4);
print(p1 == p2); // true - same values!
}The hashCode is crucial for collections like Set and Map keys. Dart's Object.hash() helper combines multiple values into a single hash code. Without a proper hashCode, your objects won't work correctly in hash-based collections even if == is overridden.
Challenge
EasyLet's build a coordinate system where points can be compared by their values rather than their memory addresses! You'll create a Coordinate class that properly implements value-based equality, making it work correctly with equality checks and hash-based collections like Set.
You'll organize your code into two files:
coordinate.dart: Create aCoordinateclass representing a point in 2D space withfinal int xandfinal int yfields. Override both the==operator andhashCodeso that two coordinates with the same x and y values are considered equal. UseObject.hash()to generate the hash code from both fields.main.dart: Import your coordinate file and demonstrate how value-based equality changes object comparison behavior:- Create two separate
Coordinateobjects, both with x:5and y:10 - Print whether they are equal using
== - Print whether they are identical (same instance) using
identical() - Create a
Set<Coordinate>and add both coordinates to it - Print the length of the set (it should be 1 since they're equal!)
- Create a third coordinate with x:
3and y:7, add it to the set - Print the final length of the set
- Create two separate
This challenge demonstrates why hashCode and == must always be overridden together. The Set uses hash codes to organize elements, so without a proper hashCode, even equal objects might be stored as duplicates!
Expected output:
true
false
1
2Cheat sheet
By default, two objects in Dart are equal only if they're the same instance in memory, not if they have the same values:
var p1 = Point(3, 4);
var p2 = Point(3, 4);
print(p1 == p2); // false - different instances!To compare objects by their values, override both the == operator and hashCode. These must always be overridden together:
class Point {
final int x, y;
Point(this.x, this.y);
@override
bool operator ==(Object other) {
if (other is! Point) return false;
return x == other.x && y == other.y;
}
@override
int get hashCode => Object.hash(x, y);
}Use Object.hash() to combine multiple values into a single hash code. The hashCode is crucial for collections like Set and Map - without it, equal objects won't work correctly in hash-based collections.
To check if two objects are the same instance (not just equal values), use identical():
print(identical(p1, p2)); // false - different instancesTry it yourself
import 'coordinate.dart';
void main() {
// TODO: Create two separate Coordinate objects, both with x: 5 and y: 10
// TODO: Print whether they are equal using ==
// TODO: Print whether they are identical (same instance) using identical()
// TODO: Create a Set<Coordinate> and add both coordinates to it
// TODO: Print the length of the set (should be 1 since they're equal!)
// TODO: Create a third coordinate with x: 3 and y: 7, add it to the set
// TODO: Print the final length of the set
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesLibraries & ImportsIntroduction to OOPClasses vs ObjectsThe this KeywordMethodsInstance VariablesConstructor BasicsRecap - Simple Calculator4Null Safety
Intro to Null SafetyNullable vs Non-NullableThe ? and ! OperatorsLate Keyword & Null SafetyNull-Aware OperatorsNull Safety in ClassesRecap - User Profile System7Abstract Classes & Interfaces
Abstract ClassesAbstract MethodsInterfaces in DartImplicit InterfacesImplementing vs ExtendingMultiple InterfacesRecap - Shape Calculator10Collections & Generics
List, Set, Map OverviewType-Safe CollectionsGeneric ClassesGeneric MethodsGeneric ConstraintsIterable & IteratorRecap - Generic Storage13Advanced OOP Concepts
Composition vs InheritanceExtension MethodsCallable ClassesSealed Classes (Dart 3)Records (Dart 3)Patterns & Matching (3.0)Enums with Methods16Project: Library Management
Project OverviewBook and User Classes2Constructors in Dart
Default ConstructorNamed ConstructorsInitializer ListsConstant ConstructorsFactory ConstructorsRedirecting ConstructorsRecap - Shape Builder5Encapsulation
Public vs Private MembersThe _ Prefix ConventionLibrary-Level PrivacyGetters & Setters DepthInformation HidingRecap - Student Records8Mixins
Introduction to MixinsCreating MixinsUsing Multiple Mixinson Keyword in MixinsMixin vs InheritanceMixin vs InterfaceRecap - Animal System11Special Methods
toString() OverridehashCode & == OverrideComparable Interfacecall() MethodnoSuchMethod OverrideRecap - Custom Collection14Design Patterns Part 1
Intro to Design PatternsSingleton PatternFactory PatternObserver PatternStrategy Pattern3Class Properties
Instance vs Static MembersFinal & Const FieldsLate VariablesStatic Methods & FieldsGetters and SettersRecap - Bank Account Manager6Inheritance
Basic InheritanceThe super KeywordMethod OverridingThe @override AnnotationThe final Class KeywordConstructors & InheritanceRecap - Employee Hierarchy9Polymorphism
Polymorphism BasicsPolymorphism via InterfacesRuntime Type CheckingThe is & as OperatorsCovariant KeywordRecap - Payment Processor