亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

特殊的 HashMap 行為

特殊的 HashMap 行為

森林海 2021-06-08 14:15:52
當我遇到以下問題時,我正在復習 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() 方法。


查看完整回答
反對 回復 2021-06-10
  • 3 回答
  • 0 關注
  • 177 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號