//根据key获取对应的val
public V get(Object key) {
Node<K,V> e;
//通过hash值,key找到目标节点再返回对应的val
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
//获取key对应的节点
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
//如果集合为空和对应的下标数组中的值为空直接返回null
//first = tab[(n - 1) & hash]数组的长度是2n次方减1后对应位全部变为1,这样为与操作永远都会在数组下标范围内不会越界
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
if (first.hash == hash && // 如果第一个节点hash与对应hash相等,并且key也相等则返回当前节点
((k = first.key) == key || (key != null && key.equals(k))))
return first;
//第一个节点的下一个节点不为null
if ((e = first.next) != null) {
//判断节点是否为树形
if (first instanceof TreeNode)
//在树形结构中查找节点并返回
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
do {//通过do...while结构遍历找对应key的节点
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
//找到节点并返回
return e;
} while ((e = e.next) != null);
}
}
//未找到对应的节点
return null;
}
get具体过程函数
最新推荐文章于 2021-11-22 20:47:06 发布