當我遇到以下問題時,我正在復習 Oracle 的 Java 認證實踐考試之一:鑒于:class MyKeys { Integer key; MyKeys(Integer k) { key = k; } public boolean equals(Object o) { return ((MyKeys) o).key == this.key; }}這個代碼片段:Map m = new HashMap();MyKeys m1 = new MyKeys(1);MyKeys m2 = new MyKeys(2);MyKeys m3 = new MyKeys(1);MyKeys m4 = new MyKeys(new Integer(2));m.put(m1, "car");m.put(m2, "boat");m.put(m3, "plane");m.put(m4, "bus");System.out.print(m.size());結果是什么?A2乙) 3C) 4D) 編譯失敗我的猜測是B,因為m1和m3對他們平等由于key引用是相同的。令我驚訝的是,答案實際上是 C。是否put()做了一些我遺漏的事情?為什么不"plane"換"car"?謝謝!
3 回答

PIPIONE
TA貢獻1829條經驗 獲得超9個贊
看看HashMap的put方法的實現就更清楚了。
// here hash(key) method is call to calculate hash.
// and in putVal() method use int hash to find right bucket in map for the object.
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
在您的代碼中,您 @Override 僅等于方法。
class MyKeys {
Integer key;
MyKeys(Integer k) {
key = k;
}
public boolean equals(Object o) {
return ((MyKeys) o).key == this.key;
}
}
要獲得輸出,您需要覆蓋 hashCode() 和 equals() 方法。
添加回答
舉報
0/150
提交
取消