HashMap的底层数据结构
接下来的源码分析可以结合这个一起看。
getNode的所有情况
源码分析
/**
* 实现Map接口的get方法和相似功能
*
* 形参hash是key的hash
* 形参key就是key
* 找到返回node对象,找不到返回null
*/
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
//成员变量table不为空 且 table的长度大于0 且 经哈希函数计算得到的存储单元不为空
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
//1.1第一个节点
//第一个节点的哈希值等于hash 且 第一个节点的key等于key
if (first.hash == hash &&
((k = first.key) == key || (key != null && key.equals(k))))
//返回第一个节点
return first;
//该存储单元链接了多个节点
if ((e = first.next) != null) {
//1.2节点以红黑树的方式链接
//第一个节点的类型是树节点类型
if (first instanceof TreeNode)
//调用专门在红黑树中查找的方法
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
//1.3节点以链表的方式链接
//以循环的方式在该链表中查找
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
//2.找不到,返回null
return null;
}