Menu
CoddyTech

Equality and Hashing

Lesson 40 of 48 in Coddy's Dart for Lua Developers course.

Lua __eq can customize table equality, but table keys still use raw identity for tables; equal-looking objects do not automatically share a key. Use a stable value such as tag text for value-based membership. Dart hashed collections instead use a class's == and hashCode together, so both must agree.

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 Lua program:

local Tag = {}
Tag.__index = Tag
function Tag.new(text) return setmetatable({text = text}, Tag) end
function Tag.__eq(a, b) return a.text == b.text end
local a, b = Tag.new('a'), Tag.new('a')
local by_text = {}
by_text[a.text], by_text[b.text] = a, b
local count = 0
for _ in pairs(by_text) do count = count + 1 end
print(count)

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 icon

Challenge

Easy

Implement 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));
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Dart for Lua Developers

Practice on your own: Online Dart compiler