get(Object key)功能:根据给定的key查找hashMap中时候有相同的key,如果有相同的key,返会该key对应的value,如果没找到,返回null.
get(Object key)中调用了 getNode(int hash, Object key),所作get()方法的重点在getNode方法上。
直接上代码+注释
public V get(Object key) {
Node<K,V> e; //定义一个node节点
return (e = getNode(hash(key), key)) == null ? null : e.value;
/*
* 根据给定的key,计算出hash值,然后根据hash和key在hashMap中查找节点元素,
* 赋值给e,e不为空则返回e对应的value,否则返回null
* */
}
/**
* Implements Map.get and related methods
*
* @param hash hash for key
* @param key the key
* @return the node, or null if none
*/
final Node<K,V> getNode(int hash, Object key) {
/*
* 定义node tab数组存放成员遍历table中的元素,
* 定义节点first,存放找到的存储在数组中的元素,
* e存放在链表中的元素,
* n节点数组tab的长度,
* K k:临时存放key的变量,判断条件中使用
* */
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
/*
* 把成员变量table不为空,赋值给tab且tab的长度>0
* 且给定hash值的位置存储的有元素,并把这个元素赋值给first
* */
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
/*
* 在上一步条件满足时,再判断当前元素的key和给定的key是否相同,
* 如果相同,说明查找到key,直接返回tan中该位置的元素
* */
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
/*
* 如果first节点有下一个元素,说明是红黑树或者链表,走一下分支
* */
if ((e = first.next) != null) { //把first的下一个节点赋值给e,e不为空然后再判断是否红黑树
if (first instanceof HashMap.TreeNode) //判断first是否红黑树
return ((HashMap.TreeNode<K,V>)first).getTreeNode(hash, key);//走红黑树分支
do { //走链表分支
/*
查找当前元素e的hash和key是否和给定的hash和key相同,查到则返回
* */
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
深入理解HashMap的get()方法
本文详细解析了HashMap的get()方法的工作原理,重点在于getNode()方法。首先,通过key计算hash值,然后在table中查找对应位置的节点。如果找到节点的key与给定key相同,则返回节点的value;否则,遍历链表或红黑树结构,查找匹配的key并返回其value。若遍历结束仍未找到,则返回null。
1843

被折叠的 条评论
为什么被折叠?



