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。
相关文章推荐
- Email--Send
- 人工智能真的要取代人类了?
- 人工智能真的要取代人类了?
- 自定义View笔记——Paint
- main执行前后
- main执行前后
- Jetbrains Product Patch or Keygen
- 【经典转载】Linux进程学习系列之五 等待进程结束wait()和waitpid()函数
- 【设计配色宝典】设计师必备七色配色宝典,附AI源文件!
- 战胜棋王后,人工智能是否可以颠覆安全?
- AEAI Portal V3.5.4升级说明,门户集成平台
- AEAI Portal V3.5.4升级说明,门户集成平台
- 深度学习: 推进人工智能的梦想
- vs2010 中添加 ActiveX Control Test Container工具
- SVN服务器提交失败 commit failed (details follow)
- POJ-1422-Air Raid-求最小路径覆盖(匈牙利算法)
- ZOJ 1094 Matrix Chain Multiplication
- 许我一个AI,给你2000年不变的爱
- JUnit——Failure与Error
- BZOJ 1260: [CQOI2007]涂色paint 区间DP