话不多说,直接上代码:
可以看出get方法里面又调用了getNode方法,如果getNode方法返回的是null,说明没找到这个key。进去getNode方法看一下:
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
//当table不为空,并且桶中不为空
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
//先检查桶中的头节点是否为我们需要get的节点
if (first.hash == hash && // always check first node
//满足key的地址相同或equals,返回头节点
((k = first.key) == key || (key != null && key.equals(k))))
return first;
//桶中不止一个节点
if ((e = first.next) != null) {
//桶中为树
if (first instanceof TreeNode)
//在树中查找,这里有机会再讲吧
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
//这里的do-while循环目的是遍历当前桶中的链表
do {
//两个key的hash值相同,并且有相同地址或者equals的key,返回目标节点
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
总结
可以说get方法是比较简单的,了解hashmap原理还是不难写出来的
传送门
深入理解HashMap(一)hashmap所用算法、构造函数
深入理解HashMap(二)put方法解析
深入理解HashMap(三)resize方法解析
深入理解HashMap(四)get方法解析
深入理解HashMap(五)remove方法解析