public V get(Object key) { // Node类型的临时变量e Node<K,V> e; // 调用getNode方法得到key对象的node节点并赋值给e // 如果e为null则返回null否则返回e的value值 return (e = getNode(hash(key), key)) == null ? null : e.value; }
final HashMap.Node<K, V> getNode ( int hash, Object key){ // 定义临时变量 HashMap.Node<K, V>[] tab; HashMap.Node<K, V> first, e; int n; K k; // 将map内的数组赋值给table // 数组不为空且数组长度不为0证明数组一经初始化 // 根据传入的hash值判断需要的节点是否为空 if ((tab = table) != null && (n = tab.length) > 0 && (first = tab[(n - 1) & hash]) != null) { // 如果第一个节点的hash值与传入hash相等且key相等 或 传入key不为空且key与第一个节点key相等 if (first.hash == hash && ((k = first.key) == key || (key != null && key.equals(k)))) // 则返回第一个节点 return first; // 将后续的节点依次赋值给e 直到e为空 if ((e = first.next) != null) { // 如果第一个节点时TreeNode节点则调用getTreeNode方法获取key对应的value if (first instanceof HashMap.TreeNode) return ((HashMap.TreeNode<K, V>) first).getTreeNode(hash, key); // 循环遍历链表直到e为空 do { // 如果e的hash值与传入hash值相等 且 if (e.hash == hash && // e的key与传入key相等 或 key不为空且key值相等 ((k = e.key) == key || (key != null && key.equals(k)))) // 返回e return e; // e依次向后移动直到e为空 } while ((e = e.next) != null); } } // hashMap没有初始化 或 没有赋值 或 节点为空 return null; }
原文:https://www.cnblogs.com/Leo-Heng/p/14614266.html