1
我已經在我的對象定義的運營商定製:HashMap中含有方法
class CharNode {
String char = "x";
String color = "#000000";
String backgroundColor = "none";
CharNode(this.char) { }
bool operator ==(CharNode other) {
return (other.char == char && other.backgroundColor == other.backgroundColor && other.color == color);
}
}
當我比較兩個CharNodes(例如)工作原理:
CharNode cn1 = new CharNode("A");
CharNode cn2 = new CharNode("A");
print((cn1 == cn2).toString());
它打印正確。
問題是與HashMap中(實施例),並在它發現一個對象:
HashMap<CharNode, int> map = new HashMap<CharNode, int>();
map[cn1] = 0;
print((map.contains(cn2)).toString());
它打印假。
問題是:如何讓HashMap使用我的自定義操作符?我必須使用forEach嗎?
所以問題是在hashCode相等?我可以手動設置hashCode嗎? – ViliX64 2014-11-06 20:04:51
是的,那正是你需要做的。有關詳細信息,請參閱http://pchalin.blogspot.ca/2014/04/defining-equality-and-hashcode-for-dart.html。 – 2014-11-06 20:10:00
爲了澄清,您不要手動設置'hashCode',而是重寫'hashCode' getter。 – Tonio 2014-11-06 20:20:27