HashMap get方法解析
开始中经常用到HashMap的put,get方法,put操作前面已经撸了,现在来撸一下get操作,以1.8为准
get源码
/**
* map.get("a") 先调用该方法
*/
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
/**
* return the node, or null if none
* 如果不为空,返回节点,为空返回null
*/
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
// 首先判断tab不为空 并且 tab.length >0
// 通过tab[(n-1) & hash]来获取当前key的对应的数据节点的hsah槽,如果为空直接返回null
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
// 如果不为空,先判断first的hash、key 是否与传入的参数一致,如果一致说明是需要取的数据,直接返回
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
// 如果不一致,并且 first.next 不为空,则进入下面的判断
if ((e = first.next) != null) {
// 如果是树 调用树的取节点方法
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
// 否则 进入循环,获取值
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}