問題描述
我只是想知道,如果 HashMap
的鍵是可變的會發生什么,下面的測試程序證明了這一點,我無法理解 equals 和 hashCode
方法何時返回true 和相同的值,為什么 hashmap.containsKey
返回 false
.
I was just wondering, what would happen if key of a HashMap
is mutable, test program below demonstrate that and I am unable to understand when both equals and hashCode
methods returns
true and same value, why does hashmap.containsKey
return false
.
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 真
推薦答案
javadoc 解釋它
注意:如果將可變對象用作映射鍵,則必須非常小心.如果對象的值以影響等于比較的方式更改,而對象是映射中的鍵,則不會指定映射的行為.
Note: great care must be exercised if mutable objects are used as map keys. The behavior of a map is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is a key in the map.
基本上,不要在 Map 中使用可變對象作為鍵,否則會被燒毀
Basically, don't use mutable objects as keys in a Map, you're going to get burnt
推斷,因為文檔可能看起來不清楚,我相信這里的相關點是以影響 equals 的方式更改",并且您似乎假設每次調用 contains 時都會調用 equals(Object).文檔沒有這么說,措辭暗示它們可能被允許緩存計算.
To extrapolate, because the docs may not appear clear, I believe the pertinent point here is `changed in a manner that affects equals', and you seem to be assuming that equals(Object) is called each time contains is invoked. The docs don't say that, the wording implies they may be allowed to cache computations.
查看source,似乎是因為您的hashCode 返回一個不同的值(以前是 5,現在是 6),可能是根據實現細節在不同的存儲桶中查找它.
Looking at the source, it seems that because your hashCode returns a different value (was 5, now 6), it's possible that it's being looked up in a different bucket based on implementation details.
這篇關于更新 Java HashMap 鍵的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!