核心库包含各种各样的实用工具类,可以用来排序、映射值和迭代。
比较对象
实现 Comparable 接口来表明一个对象可以与其他对象进行比较,通常用来排序。方法 compareTo() 返回 < 0 的值来表示“更小”、0 表示相等、> 0 的值表示“更大”。
class Line implements Comparable<Line> {
final int length;
const Line(this.length);
int compareTo(Line other) => length - other.length;
}
void main() {
var short = const Line(1);
var long = const Line(100);
assert(short.compareTo(long) < 0);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
实现 map 的键
Dart 中的每一个对象都提供了一个整数类型的 hash 码,因此可以用来作为一个 map 的键。然而,你可以重载 hashCode 的 getter 来生成一个自定义的 hash 码。如果你这样做,你必须同时重载 == 操作符。相等的对象(使用 ==)必须拥有相同的 hash 码。一个 hash 码不一定要是唯一的,但是应该合理地分发。
class Person {
final String firstName, lastName;
Person(this.firstName, this.lastName);
// 使用 Effective Java 第11章中的策略重载 hash 码
int get hashCode {
int result = 17;
result = 37 * result + firstName.hashCode;
result = 37 * result + lastName.hashCode;
return result;
}
// 如果你重载 hash 码,你通常要重载 == 运算符
bool operator ==(dynamic other) {
if (other is! Person) return false;
Person person = other;
return (person.firstName == firstName &&
person.lastName == lastName);
}
}
void main() {
var p1 = Person('Bob', 'Smith');
var p2 = Person('Bob', 'Smith');
var p3 = 'not a person';
assert(p1.hashCode == p2.hashCode);
assert(p1 == p2);
assert(p1 != p3);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
迭代
Iterable 类 和 Iterator 类 提供了 for-in 循环。当你想要创建一个提供 for-in 循环的迭代器类时,继承(如果可以)或者实现 Iterable。实现 Iterator 来定义真正的迭代能力。
class Process {
// 代表一个处理...
}
class ProcessIterator implements Iterator<Process> {
Process get current => ...
bool moveNext() => ...
}
// 一个虚拟的类,它继承了 Iterable 的子类,使你可以
// 从所有的处理中迭代
class Processes extends IterableBase<Process> {
final Iterator<Process> iterator = ProcessIterator();
}
void main() {
// Iterable 对象可以使用 for-in
for (var process in Processes()) {
// 对 process 做一些处理
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24