您的位置:首页 > 大数据 > 人工智能

HashMap的containskey源码分析

2016-03-11 10:53 369 查看
HashMap
作为util包中比较常用的一个数据结构,充分理解内部代码的逻辑是有很必要的,这里做一个对
HashMap
containsKey
函数的源码分析笔记。

containsKey
的代码如下:

/**
* Returns <tt>true</tt> if this map contains a mapping for the
* specified key.
*
* @param   key   The key whose presence in this map is to be tested
* @return <tt>true</tt> if this map contains a mapping for the specified
* key.
*/
public boolean containsKey(Object key) {
return getEntry(key) != null;
}


内部调用的是
getEntry
函数,进入
getEntry
函数:

/**
* Returns the entry associated with the specified key in the
* HashMap.  Returns null if the HashMap contains no mapping
* for the key.
*/
final Entry<K,V> getEntry(Object key) {
if (size == 0) {
return null;
}

int hash = (key == null) ? 0 : hash(key);
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 != null && key.equals(k))))
return e;
}
return null;
}


可以看到主要的逻辑在:

if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;


而这里值得注意的是
||
前面的Object的
==
key.equals(k)
key
是一个
Object
,所以默认的
equals
方法为:

public boolean equals(Object obj) {
return (this == obj);
}


所以要注意没有重写
equals
方法的
Object
作为
HashMap``key
的情况:

如数组作为
key
时,相同内容的
key
,但是属于不同的对象,比较的结果都为
false
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: