首页 > 其他 > 详细

hashMap.get()源码解析

时间:2021-04-03 23:18:53      阅读:34      评论:0      收藏:0      [点我收藏+]

 get()源码解析

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;
    }
    

 

getNode(hash(key) , key)源码解析

        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;
        }

 

hashMap.get()源码解析

原文:https://www.cnblogs.com/Leo-Heng/p/14614266.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!