关于HashMap
2008-07-07 10:19
106 查看
HashMap作为Map接口的一个具体实现类,我想很多人都在使用。但是不知道有没有人发现,这个实现并没有完全按照接口说明来实现。比如:方法 get。接口说明如下:
Returns the value to which the specified key is mapped, or
More formally, if this map contains a mapping from a key
If this map permits null values, then a return value of
Parameters:
如果此映射包含一个满足
但是经本人测试发现,无论怎样重载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有心为之,还是说明文档没有写全,亦或是我的理解有误。
get
V get(Object key)
Returns the value to which the specified key is mapped, or
nullif this map contains no mapping for the key.
More formally, if this map contains a mapping from a key
kto a value
vsuch 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
nulldoes 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
containsKeyoperation 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
nullif 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有心为之,还是说明文档没有写全,亦或是我的理解有误。
相关文章推荐
- 关于Java String, StringBuilder, StringBuffer, Hashtable, HashMap的面试题
- Java中关于HashMap的使用和遍历
- 记录关于HashMap线程不安全示例
- Java和guava关于hashmap在初始化的时候最好给个初始容量
- 关于HashMap的面试题
- 关于hashmap的散列程度分析
- 关于HashMap底层的一些问题
- 关于HashMap、LinkedHashMap与TreeMap
- 关于hashmap
- 4、关于HashMap在多线程下的不安全分析
- 关于jdk1.8的容器hashmap中的entrySet()函数实现。
- 自己做的demo--关于HashMap
- Java中关于HashMap的使用和遍历
- 关于Java中HashMap和HashSet
- 关于HashMap,HashTable,HashSet浅析
- 关于HashMap的putAll(Map m)方法的使用问题
- 关于HashTable,HashMap和TreeMap的几点心得
- 关于 HashMap 1.8 的重大更新
- Java中关于WeakReference和WeakHashMap的理解
- Java源码分析:关于 HashMap 1.8 的重大更新