2014-11-06 43 views
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嗎?

回答

4

除了定義相等之外,還必須提供hashCode實現。

由於HashMap docs狀態:

一個HashMap的鍵必須有一致的Object.operator ==和 的hashCode實現。這意味着==運算符必須在鍵上定義 一個穩定的等價關係(反射,對稱,可傳遞,並且隨着時間的推移一致),並且該hashCode必須是 ,對於被==視爲相等的對象相同。

+0

所以問題是在hashCode相等?我可以手動設置hashCode嗎? – ViliX64 2014-11-06 20:04:51

+0

是的,那正是你需要做的。有關詳細信息,請參閱http://pchalin.blogspot.ca/2014/04/defining-equality-and-hashcode-for-dart.html。 – 2014-11-06 20:10:00

+2

爲了澄清,您不要手動設置'hashCode',而是重寫'hashCode' getter。 – Tonio 2014-11-06 20:20:27