我不明白一个集合如何确定两个对象何时相等.更具体地说,add一个集合的方法何时真正添加一个新对象,何时它不是一个新对象,因为该对象已经在集合中?
例如,我有以下类中的对象:
class Action {
final Function function;
final String description;
Action(this.function, this.description);
call() => function();
toString() => description;
}
Run Code Online (Sandbox Code Playgroud)
现在我认为以下集合将包含2个元素,因为其中2个是相等的:
void main() {
Set<Action> actions = new Set()
..add(new Action(() => print("a"), "print a"))
..add(new Action(() => print("a"), "print a"))
..add(new Action(() => print("b"), "print b"));
}
Run Code Online (Sandbox Code Playgroud)
但相反,这个集合包含3个Action对象.看演示.如何确保在集合中看到相等的对象相等?
Gün*_*uer 11
有关operator==Dart 的全面介绍,请参阅http://work.j832.com/2014/05/equality-and-dart.html
它只检查它们是否相等a == b您可以覆盖==运算符以自定义此行为.请记住,hashCode在覆盖==运算符时也应该重写.
class Action {
@override
bool operator==(other) {
// Dart ensures that operator== isn't called with null
// if(other == null) {
// return false;
// }
if(other is! Action) {
return false;
}
return description == (other as Action).description;
}
// hashCode must never change otherwise the value can't
// be found anymore for example when used as key
// in hashMaps therefore we cache it after first creation.
// If you want to combine more values in hashCode creation
// see http://stackoverflow.com/a/26648915/217408
// This is just one attempt, depending on your requirements
// different handling might be more appropriate.
// As far as I am aware there is no correct answer for
// objects where the members taking part of hashCode and
// equality calculation are mutable.
// See also http://stackoverflow.com/a/27609/217408
int _hashCode;
@override
int get hashCode {
if(_hashCode == null) {
_hashCode = description.hashCode
}
return _hashCode;
}
// when the key (description) is immutable and the only
// member of the key you can just use
// int get hashCode => description.hashCode
}
Run Code Online (Sandbox Code Playgroud)
试试DartPad
| 归档时间: |
|
| 查看次数: |
1067 次 |
| 最近记录: |