Menu
CoddyTech

相等性与哈希

Coddy 面向 Lua 开发者的 Dart 课程的第 40 课,共 48 课。

Lua 的 __eq 可以自定义表的相等性,但表仍使用原始标识作为表键;外观相同的对象不会自动共用一个键。要按值判断成员关系,可以使用稳定的值,例如标签文本。Dart 的哈希集合则会同时使用类的 == 和 hashCode,因此两者必须一致。

相等的对象必须具有相同的 hashCode 值,但哈希冲突并不能证明对象相等。对象存储在哈希集合中时,要保持与相等性相关的状态稳定。

完整的 Lua 程序:

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)

完整的 Dart 程序:

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

挑战

简单

实现不可变的 Key(int row,int column),并提供 final 公共字段。两个 Key 当且仅当两个坐标都相同时才相等。以一致的方式重写 operator == 和 hashCode。输入为完整的整数坐标对。使用 Set 统计不同的键,并返回数量。坐标范围为 -100 到 100。

不要在可编辑文件中打印内容。提供的 exercise.dart 会解析输入并返回输出;锁定的驱动程序会独立测试公共 API,并在结果后打印一个换行符。

你的代码应写在 Key.dart 和 exercise.dart 中。main.dart 中包含提供的输入/输出代码,不能编辑。

亲手试试

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 icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向 Lua 开发者的 Dart中的所有课

自己练习: Dart 在线编译器