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 valuev
such that(key==null ? k==null : key.equals(k))
, then this method returnsv
; otherwise it returnsnull
. (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 tonull
. ThecontainsKey
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有心为之,还是说明文档没有写全,亦或是我的理解有误。