Dart 更改检查贴图键是否相等的方式
我有以下代码:Dart 更改检查贴图键是否相等的方式,dart,Dart,我有以下代码: class KeyClass { int property; KeyClass(this.property); } void main() { KeyClass kc1 = KeyClass(1); KeyClass kc2 = KeyClass(2); Map<KeyClass, String> map = Map(); map[kc1] = 'hello'; map[kc2] = 'world'; ... } 这在Dart语
class KeyClass {
int property;
KeyClass(this.property);
}
void main() {
KeyClass kc1 = KeyClass(1);
KeyClass kc2 = KeyClass(2);
Map<KeyClass, String> map = Map();
map[kc1] = 'hello';
map[kc2] = 'world';
...
}
这在Dart语言中可能吗?默认映射实现是LinkedHashMap,因此它依赖于计算密钥的哈希代码。有几种方法可以使密钥比较相等:
实现KeyClass.operator==和KeyCode.hashCode:
类键类{
int属性;
keyclass.property;
布尔运算符==动态其他{
返回runtimeType==other.runtimeType&&property==other.property;
}
int get hashCode=>property.hashCode;
}
直接使用LinkedHashMap。LinkedHashMap的构造函数允许为计算等式和哈希代码提供自定义回调:
bool keyEqualsKeyClass k1,KeyClass k2=>k1.property==k2.property;
int keyHashCodeKeyClass k=>k.property.hashCode;
Map Map=LinkedHashMap
equals:keyEquals,
hashCode:keyHashCode,
;
print(map[kc1]); // prints 'hello'
print(map[KeyClass(1)]); // prints 'null', should print 'hello' too!