我不明白集合是如何确定两个对象何时相等的。更具体地说,集合的add
方法什么时候真正添加了一个新对象,什么时候不作为一个新的对象,因为对象已经在集合中了?
例如,我有来自以下类的对象:
class Action {
final Function function;
final String description;
Action(this.function, this.description);
call() => function();
toString() => description;
}
现在我认为下面的集合将包含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"));
}
但是,该集合包含3个Action
对象。请参阅演示。如何确保相等的对象在集合中被视为相等?
有关Dart中operator==
的全面综述,请参阅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
}
试试DartPad