Jdk1.8下HashMap常用方法的源码分析

1.首先是从hashmap中put元素开始分析

 HashMap<String, String> map = new HashMap<>();
 map.put("123", "1");
 map.get("123");

2.点击put方法进入到里面

public V put(K key, V value) {
  // hash(key) 计算key对应的hash值
  return putVal(hash(key), key, value, false, true);
}

继续点击putVal方法

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        // 首先判断数组是否为空,假如为空则进行初始化操作,这里的resize方法可以初始化或者扩容操作
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        // 获取key对应数组位置的值是否为null,如果为null则创建一个node放在数组i位置上
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            // 如果不为null,并且key相等,然后将对应的node赋值给e
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            // 如果创建的p属于树节点实例,则进行树下面插入
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
            	// 否则,就是链表下插入,遍历链表
                for (int binCount = 0; ; ++binCount) {
                	// 如果遍历到最后一个,则使用尾插法插入元素
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        // 如果插入的元素个数超过8个,则进行树化操作
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    // 如果遍历过程中找到key相等的元素,则跳出循环
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            // 假如e不为null,则覆盖旧的,并返回旧的value
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        // 判断实际容量是否大于阈值,假如大于,则进行扩容
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        // 没有找到则返回null
        return null;
 }

3.其中点击resize方法,查看一下里面的大概逻辑

 final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table;
        // 首先获取数组的长度
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        int oldThr = threshold;
        int newCap, newThr = 0;
        // 假如数组长度大于0进入下面分支
        if (oldCap > 0) {
        	// 如果数组长度大于MAXIMUM_CAPACITY,则threshold = Integer.MAX_VALUE;
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            // 否则数组长度翻一倍,并且重新计算阈值
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; // double threshold
        }
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;
        // 如果数组长度为0,则数组长度默认为16,并且赋值新的阈值
        else {               // zero initial threshold signifies using defaults
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
        // 计算阈值,下面赋值
        if (newThr == 0) {
            float ft = (float)newCap * loadFactor;
            newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                      (int)ft : Integer.MAX_VALUE);
        }
        threshold = newThr;
        @SuppressWarnings({"rawtypes","unchecked"})
        // 上面是初始化操作
        Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];


		// 下面是扩容操作
        table = newTab;
        if (oldTab != null) {
        	// 遍历旧的数组上的元素
            for (int j = 0; j < oldCap; ++j) {
                Node<K,V> e;
                if ((e = oldTab[j]) != null) {
                    oldTab[j] = null;
                    // 如果当前位置没有下个元素,则直接进行根据新的数组长度计算hash,进行存放
                    if (e.next == null)
                        newTab[e.hash & (newCap - 1)] = e;
                    // 如果当前位置有下个元素,并且是TreeNode类型,则进行红黑树插入  
                    else if (e instanceof TreeNode)
                        ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
					// 如果如果当前位置有下个元素,并且是链表类型,则进行转移到新的数组中,这里逻辑是拆分为两个链表重新插入到新的数组中,一个位置是newTab[j],另外一个位置是newTab[j + oldCap]
                    else { // preserve order
                        Node<K,V> loHead = null, loTail = null;
                        Node<K,V> hiHead = null, hiTail = null;
                        Node<K,V> next;
                        do {
                            next = e.next;
                            if ((e.hash & oldCap) == 0) {
                                if (loTail == null)
                                    loHead = e;
                                else
                                    loTail.next = e;
                                loTail = e;
                            }
                            else {
                                if (hiTail == null)
                                    hiHead = e;
                                else
                                    hiTail.next = e;
                                hiTail = e;
                            }
                        } while ((e = next) != null);
                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead;
                        }
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
}

4.其中点击上面((TreeNode<K,V>)e).split(this, newTab, j, oldCap);这段代码的的split方法

 final void split(HashMap<K,V> map, Node<K,V>[] tab, int index, int bit) {
            TreeNode<K,V> b = this;
            // Relink into lo and hi lists, preserving order
            TreeNode<K,V> loHead = null, loTail = null;
            TreeNode<K,V> hiHead = null, hiTail = null;
            int lc = 0, hc = 0;
            // 这里是从数组的元素开始,也就是树的根节点开始遍历,拆分为两个高位和低位的链表
            for (TreeNode<K,V> e = b, next; e != null; e = next) {
                next = (TreeNode<K,V>)e.next;
                e.next = null;
                if ((e.hash & bit) == 0) {
                    if ((e.prev = loTail) == null)
                        loHead = e;
                    else
                        loTail.next = e;
                    loTail = e;
                    ++lc;
                }
                else {
                    if ((e.prev = hiTail) == null)
                        hiHead = e;
                    else
                        hiTail.next = e;
                    hiTail = e;
                    ++hc;
                }
            }
			// 如果低位链表个数小于6,则进行转化为链表
            if (loHead != null) {
                if (lc <= UNTREEIFY_THRESHOLD)
                    tab[index] = loHead.untreeify(map);
                else {
               		// 如果不小于6,并且hiHead 为null,则将整个树移动到新的数组上
                    tab[index] = loHead;
                    // 如果hiHead 不为null,则将低位转为红黑数
                    if (hiHead != null) // (else is already treeified)
                        loHead.treeify(tab);
                }
            }
            // 如果高位链表个数小于6,则进行转化为链表
            if (hiHead != null) {
                if (hc <= UNTREEIFY_THRESHOLD)
                    tab[index + bit] = hiHead.untreeify(map);
                else {
                	// 如果不小于6,并且loHead  为null,则将整个树移动到新的数组上
                    tab[index + bit] = hiHead;
                    // 如果loHead  不为null,则将高位转为红黑数
                    if (loHead != null)
                        hiHead.treeify(tab);
                }
            }
}

5.再点击查看一下get方法

 public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
}
final Node<K,V> getNode(int hash, Object key) {
        Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
        // 判断数组的是否为null,并且数组的长度是否大于0,还判断key对应数组位置上的元素是否为null
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {
            // 如果当前数组位置上元素的Key和传入进来的key相等,则返回当前数组上的元素
            if (first.hash == hash && // always check first node
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
            // 遍历当前数组上元素的下面的元素
            if ((e = first.next) != null) {
            	// 如果当前数组上的元素是TreeNode,则去遍历红黑数获取元素(二叉查找树的方式)
                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);
            }
        }
        // 如果没找到,则返回null
        return null;
}

6.继续看一下remove方法

 public V remove(Object key) {
        //定义一个Node类型的变量e
        Node<K,V> e;
        //调用removeNode()删除key对应的节点,返回值就是被删除的节点,如果为null,就说明没有对应的节点,返回null,否则返回删除节点的value值
        return (e = removeNode(hash(key), key, null, false, true)) == null ?
            null : e.value;
}



/**
* @param hash key的hash值,通过hash(key)方法取得这个值
* @param key 要删除的键值对的key值
* @param value 要删除的键值对的value值,HashMap的remove方法默认传null
* @param matchValue 如果为true,则传进来的value要等于key对应的被删除节点的value值才能删除,也就是说搜索到的节点的key和value要等于入参的key和value值才能被删除,否则反之。HashMap的remove方法默认传false
* @param movable 删除后是否移动节点,如果为false,则不移动,HashMap的remove方法默认传true
* */
final Node<K,V> removeNode(int hash, Object key, Object value,
                               boolean matchValue, boolean movable) {
        //定义几个变量                       
        Node<K,V>[] tab; Node<K,V> p; int n, index;
        //首先是判断数组table不能为空且长度要大于0,同时把数组长度tab.length赋值给n
        if ((tab = table) != null && (n = tab.length) > 0 &&
        //其次是通过[(n - 1) & hash]获取key对应的索引并赋值index变量,同时数组中的这个索引要有值,然后赋值给p变量,p不为null的话
            (p = tab[index = (n - 1) & hash]) != null) {
            //定义几个变量
            Node<K,V> node = null, e; K k; V v;
            //如果要删除的key值和p节点的key值相等的话(hash相等,key相等或者equals结果相等)
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                //把p节点赋值给node变量
                node = p;
            //否则就取得p的后继节点,并赋值给e变量,看下e是不是为null,不为null的话
            else if ((e = p.next) != null) {
                //如果p节点类型已经是树节点类型了
                if (p instanceof TreeNode)
                    //就通过getTreeNode()方法去树中取得相应节点,并赋值给node变量 
                    node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
                //如果不是树节点,就说明还是链表结构    
                else {
                    do {
                        //如果要删除的key值和e节点的key值相等的话(hash相等,key相等或者equals结果相等)
                        if (e.hash == hash &&
                            ((k = e.key) == key ||
                             (key != null && key.equals(k)))) {
                             //说明e就是我们要删除的节点,把e赋值给node变量
                            node = e;
                            break;
                        }
                        //这里就是把e赋值给p,保证p一直会是p的前驱节点,这样如果删除了e节点后,就方便修改指针,让指针指向被删除节点的下一个节点,这样链表才是连续的,不会断开
                        p = e;
                      //获取e节点的后继节点,然后赋值给e,不为空则进入循环体   
                    } while ((e = e.next) != null);
                }
            }
            //这里我们可以发现,只要有找到对应的删除节点就会赋值给node,所以如果node不等于null,说明有可以删除的节点,同时matchValue默认是false,所以!matchValue满足前面的条件直接短路了,不用走后面判断的逻辑了
            if (node != null && (!matchValue || (v = node.value) == value ||
                                 (value != null && value.equals(v)))) {
                //如果node节点是树类型的                  
                if (node instanceof TreeNode)
                    //那么就调用removeTreeNode()方法去删除这个节点,movable默认为true,所以删除后要移动节点
                    ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
                //如果node变量等于p节点,这里的p节点代表的是链表首节点,所以要删除的是首节点  
                else if (node == p)
                    //那么就要先把这个首节点对应的索引里的node对象,赋值成p节点的后继节点,这样之后才能删除p节点也就是首节点
                    tab[index] = node.next;
                else
                //如果要删除的节点不是链表首节点的话,这里的p其实是e的前驱节点,node其实就是e,所以我们如果要把e删除,就要让原来p中指向e的指针,指向e的下一个节点,链表就能够连续了
                    p.next = node.next;
                //做了删除操作,就要把该HashMap的修改次数加1    
                ++modCount;
                //键值对总数减一
                --size;
                //HashMap中没有具体实现,这是给LinkedHashMap用的,不用关心
                afterNodeRemoval(node);
                //返回要被删除的节点node
                return node;
            }
        }
        //如果找不到要删除的节点,则返回null
        return null;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值