为了账号安全,请及时绑定邮箱和手机立即绑定

特殊的 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 关注
  • 165 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信