当我遇到以下问题时,我正在复习 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 回答
![?](http://img1.sycdn.imooc.com/545863e80001889e02200220-100-100.jpg)
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
提交
取消