更改检查地图项是否相等的方式 [英] Change how map keys are checked for equality
本文介绍了更改检查地图项是否相等的方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码:
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';
...
}
我的目标是使以下两行从我的 map
中获得相同的值:
My goal is to for the following two lines to get the same value from my map
:
print(map[kc1]); // prints 'hello'
print(map[KeyClass(1)]); // prints 'null', should print 'hello' too!
Dart语言有可能吗?
Is this possible in Dart language?
推荐答案
默认的 Map
实现是 LinkedHashMap
,因此它依赖于计算键的哈希码.有几种方法可以使您的键比较相等:
The default Map
implementation is a LinkedHashMap
, so it relies on computing hash codes for the keys. There are a few ways you could make your keys compare equal:
-
实施
KeyClass.operator ==
和KeyCode.hashCode
:
class KeyClass {
int property;
KeyClass(this.property);
bool operator ==(dynamic other) {
return runtimeType == other.runtimeType && property == other.property;
}
int get hashCode => property.hashCode;
}
直接使用 LinkedHashMap
. LinkedHashMap
的构造函数允许提供自定义回调以计算相等性和哈希码:
Use LinkedHashMap
directly. LinkedHashMap
's constructor allows providing custom callbacks for computing equality and hash codes:
bool keyEquals(KeyClass k1, KeyClass k2) => k1.property == k2.property;
int keyHashCode(KeyClass k) => k.property.hashCode;
Map<KeyClass, String> map = LinkedHashMap<KeyClass, String>(
equals: keyEquals,
hashCode: keyHashCode,
);
这篇关于更改检查地图项是否相等的方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文