Equality and Hashing
Lesson 40 of 48 in Coddy's Dart for C Developers course.
C has no == for structs and no built-in hash table, so a hashed set needs equality and hash functions you write and pass to it. Comparing with memcmp or pointer equality is a classic bug: it compares padding bytes or addresses, not the text a member points to. Dart == and hashCode overrides play those roles for Set and Map keys. Equal values must have equal hashes, but equal hashes do not prove equality. Keep fields used by stored keys stable.
Equal objects must have equal hashCode values, but a hash collision does not prove equality. Keep equality-relevant state stable while objects are stored in hashed collections.
Complete C program:
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
struct tag {
const char *text;
};
static bool tag_equals(const struct tag *a, const struct tag *b) { return strcmp(a->text, b->text) == 0; }
static unsigned tag_hash(const struct tag *t) {
unsigned h = 5381;
for (const char *p = t->text; *p; p++) h = h * 33 + (unsigned char)*p;
return h;
}
struct tag_set {
struct tag items[8];
unsigned hashes[8];
int size;
};
static void tag_set_add(struct tag_set *s, struct tag t) {
unsigned h = tag_hash(&t);
for (int i = 0; i < s->size; i++)
if (s->hashes[i] == h && tag_equals(&s->items[i], &t)) return;
s->items[s->size] = t;
s->hashes[s->size++] = h;
}
int main(void) {
char first[] = "a", second[] = "a"; /* equal text at two addresses */
struct tag_set s = {0};
tag_set_add(&s, (struct tag){first});
tag_set_add(&s, (struct tag){second});
printf("%d\n", s.size);
return 0;
}
Complete Dart program:
class Tag{final String text;const Tag(this.text);@override bool operator ==(Object other)=>other is Tag&&text==other.text;@override int get hashCode=>text.hashCode;}
void main(){print({Tag('a'),Tag('a')}.length);}Challenge
EasyImplement immutable Key(int row,int column) with final public fields. Two Keys are equal exactly when both coordinates match. Override operator == and hashCode consistently. Input is complete integer coordinate pairs. Count distinct keys using a Set and return count. Coordinates range from -100 to 100.
Do not print from editable files. The supplied exercise.dart parses input and returns output; the locked driver independently probes the public APIs and prints the result with one newline.
Your code goes in Key.dart, exercise.dart. main.dart holds the supplied input/output code and cannot be edited.
Try it yourself
import 'dart:io';
import 'dart:convert';
import 'exercise.dart';
import 'Key.dart';
void check(bool condition){if(!condition)throw StateError('Public API contract failed');}
Future<void> main() async {
final raw=await stdin.transform(utf8.decoder).join();
final input=raw.replaceFirst(RegExp(r'\r?\n$'),'');
final a=Key(2,3),b=Key(2,3);check(a==b && a.hashCode==b.hashCode && a!=Key(3,2));check({a,b}.length==1);
stdout.writeln(solve(input));
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Dart for C Developers
1First Dart Programs
Run Dart FilesOutput and CommentsImports and LibrariesBindings and TypesNumeric OperationsRecap: Parcel Invoice4Collection Pipelines
Iterables and LazinessMaps and Missing KeysSets and MembershipClosures and CallbacksSorting and ComparatorsRecap: Word Inventory3Functions and Values
Functions and ReturnsNamed ParametersNull SafetyStrings and UnicodeLists and MutationRecap: Record Readings6Objects and State
Classes and InstancesConstructors and FactoriesProperties and PrivacyIdentity and CopiesComposition Across FilesRecap: Bounded Counter9Parcel Depot Project
Depot: Valid ItemsDepot: Register StockPractice on your own: Online Dart compiler