我只是想知道,如果HashMap
的關鍵是可變的,會發生什麼,下面的測試程序證明,我無法理解當兩個平等的,hashCode
方法返回 真實值相同,爲什麼hashmap.containsKey
返回false
。更新Java的HashMap的關鍵
public class MutableKeyHashMap {
public static void main(String []a){
HashMap<Mutable, String> map = new HashMap<Mutable, String>();
Mutable m1 = new Mutable(5);
map.put(m1, "m1");
Mutable m2 = new Mutable(5);
System.out.println(map.containsKey(m2));
m2.setA(6);
m1.setA(6);
Mutable m3 = map.keySet().iterator().next();
System.out.println(map.containsKey(m2)+" "+m3.hashCode()+" "+m2.hashCode()+" "+m3.equals(m2));
}
}
class Mutable {
int a;
public Mutable(int a) {
this.a = a;
}
@Override
public boolean equals(Object obj) {
Mutable m = (Mutable) obj;
return m.a == this.a ? true : false;
}
@Override
public int hashCode(){
return a;
}
public void setA(int a) {
this.a = a;
}
public int getA() {
return a;
}
}
此輸出:
真 假6 6真正
你可能會發現這篇關於Python的方法很有趣:http://pyfaq.infogami.com/why-must-dictionary-keys-be-immutable – jtoberon