关于HashMap

HashMap作为Map接口的一个具体实现类,我想很多人都在使用。但是不知道有没有人发现,这个实现并没有完全按照接口说明来实现。比如:方法 get。接口说明如下:

get

V get(Object key)
Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

More formally, if this map contains a mapping from a key k to a value v such that (key==null ? k==null : key.equals(k)), then this method returns v; otherwise it returns null. (There can be at most one such mapping.)

If this map permits null values, then a return value of null does not necessarily indicate that the map contains no mapping for the key; it's also possible that the map explicitly maps the key to null. The containsKey operation may be used to distinguish these two cases.

Parameters:
key - the key whose associated value is to be returned
Returns:
the value to which the specified key is mapped, or null if this map contains no mapping for the key
Throws:
ClassCastException - if the key is of an inappropriate type for this map (optional)
NullPointerException - if the specified key is null and this map does not permit null keys (optional)
请注意红色文字,这部分翻译过来说的是: 如果此映射包含一个满足 (key==null ? k==null : key.equals(k)) 的从 k 键到 v 值的映射关系,则此方法返回 v;否则返回 null。(最多只能有一个这样的映射关系。) 但是经本人测试发现,无论怎样重载key的equals方法,就是不能得到相应的结果,后来查询源代码,发现HashMap首先要验证hashcode是否相同,如果相同,才验证equals。实现如下: public V get(Object key) {         if (key == null)             return getForNullKey();         int hash = hash(key.hashCode());         for (Entry<K,V> e = table[indexFor(hash, table.length)];              e != null;              e = e.next) {             Object k;             if (e.hash == hash && ((k = e.key) == key || key.equals(k)))                 return e.value;         }         return null;     } 注意红色语句。 同样,对于containsKey也存在相同的实现。 不知道这是sun有心为之,还是说明文档没有写全,亦或是我的理解有误。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值