Menu
CoddyTech

相等性与哈希

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

R 中的 unique 根据其集合规则去除重复值;它不会在 S3 对象上调用 Dart 风格的 hashCode getter。此处的文本键提供了基于值的去重。Dart 类定义 == 和 hashCode 以用于自定义值键。相等的键需要相等的哈希值,且在该约定中使用的字段在存储期间必须保持稳定。

相等的对象必须具有相等的 hashCode 值,但哈希冲突并不意味着相等。当对象存储在哈希集合中时,请保持与相等性相关的状态稳定。

完整的 R 程序:

new_tag <- function(text) structure(list(text = text), class = "tag")
tags <- list(new_tag("a"), new_tag("a"))
keys <- vapply(tags, function(x) x$text, character(1))
cat(length(unique(keys)), "\n", sep = "")

完整的 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 统计不同的 key 数量并返回该数量。坐标范围在 -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自我测试

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

面向 R 开发者的 Dart 课程中的所有课

自己练习: Dart 在线编译器