zoukankan      html  css  js  c++  java
  • java源码HashMap源码分析

    这次开始分析JDK8中的HashMap源码。

    首先理解HashMap中几个关键变量,

    TREEIFY_THRESHOLD  链表转换红黑树扩容值 table 数组+链表+红黑树  size 当前存储数量  loadFactor加载因子 threshold 扩容值等于table长度*loadFactor。

    首先判断put(K k,V v)方法,会调用 putVal(...)方法

       final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                       boolean evict) {
            // tab 就是 node数组  p是key查询已经存在的数组node节点
            Node<K,V>[] tab; Node<K,V> p; int n, i;
            //首先判断表是否为空 如果表为空则开始初始化node数组,并将node数组长度赋予n
            if ((tab = table) == null || (n = tab.length) == 0)
                n = (tab = resize()).length;
            // key的hash值与上node数组长度-1 数组扩容后总是2的N次方 这里是对取模的优化
            if ((p = tab[i = (n - 1) & hash]) == null) 
                // 如果hash取模后 数组位为空,则新建一个node节点赋予数组节点。
                tab[i] = newNode(hash, key, value, null);
            else {
                Node<K,V> e; K k;
                // 判断如何hash值相同 并且key.equals(k),则代表是一个key 则将 p赋值给e
                if (p.hash == hash &&
                    ((k = p.key) == key || (key != null && key.equals(k))))
                    e = p;
                // 如果是红黑树 开始插入红黑树返回赋值给e
                else if (p instanceof TreeNode)
                    e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
                else {
                    // 循环遍历到node节点p的链表尾部
                    for (int binCount = 0; ; ++binCount) {
                        // 如何p的next节点为空 e==p==null
                        if ((e = p.next) == null) {
                            // 直接新建node节点赋予p的next节点
                            p.next = newNode(hash, key, value, null);
                            // 如果链表长度大于  TREEIFY_THRESHOLD(转换为红黑树) 则转换为红黑树
                            if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                                treeifyBin(tab, hash);
                            break;
                        }
                        // 如果key hash相同 && key.equals(k) 则结束循环 此时e!=null
                        if (e.hash == hash &&
                            ((k = e.key) == key || (key != null && key.equals(k))))
                            break;
                        p = e;
                    }
                }
                // 处理链表中 e不为null 的情况 onlyIfAbsent==false || oldValue==null 则直接覆盖old value
                if (e != null) { // existing mapping for key
                    V oldValue = e.value;
                    if (!onlyIfAbsent || oldValue == null)
                        e.value = value;
                    // 这个方法hashMap没有涉及到 这是为了扩展视图
                    afterNodeAccess(e);
                    // 最后返回旧的值
                    return oldValue;
                }
            }
            // 增加修改记录
            ++modCount;
            // 如果map中当前size大于threshold 则开始扩容
            if (++size > threshold)
                resize();
            // 控制节点插入 这是为了扩展视图
            afterNodeInsertion(evict);
            return null;
        }

    再分析一下get(K k)方法

       final Node<K,V> getNode(int hash, Object key) {
            // tab 当前node数组 first 当存在hash碰撞时候的第一个node节点 e记录next节点 n node数组长度, k 是记录key
            Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
            // 如果表为空 则直接返回null
            if ((tab = table) != null && (n = tab.length) > 0 &&
                (first = tab[(n - 1) & hash]) != null) {
                // 如果第一个key的hash相同 && key != null && key.equals(k)) 则返回当前node节点
                if (first.hash == hash && // always check first node
                    ((k = first.key) == key || (key != null && key.equals(k))))
                    return first;
                // 如果fist.next节点不为空
                if ((e = first.next) != null) {
                    // 判断当前节点是红黑树 如果是 走红黑树搜素 返回当前节点
                    if (first instanceof TreeNode)
                        return ((TreeNode<K,V>)first).getTreeNode(hash, key);
                    // 循环遍历next节点 并判断  如果key相同 则返回节点  直到 next节点为空
                    do {
                        if (e.hash == hash &&
                            ((k = e.key) == key || (key != null && key.equals(k))))
                            return e;
                    } while ((e = e.next) != null);
                }
            }
            return null;
        }

    再看一下删除节点 remove(Object key)方法

     final Node<K,V> removeNode(int hash, Object key, Object value,
                                   boolean matchValue, boolean movable) {
            // tab node数组 p当前key取模存在的数组角标node节点 n 数组的长度 index
            Node<K,V>[] tab; Node<K,V> p; int n, index;
            // 如果不为空 &&  hash取模定位数组角标node存在
            if ((tab = table) != null && (n = tab.length) > 0 &&
                (p = tab[index = (n - 1) & hash]) != null) {
                // node 纪录查询匹配的节点
                Node<K,V> node = null, e; K k; V v;
                // 如果key hash相同 && key != null && key.equals(k) 则将 p赋予node节点
                if (p.hash == hash &&
                    ((k = p.key) == key || (key != null && key.equals(k))))
                    node = p;
                else if ((e = p.next) != null) {
                    // 如果节点是红黑树  则走红黑树查询
                    if (p instanceof TreeNode)
                        node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
                    // 循环遍历 如果找到相同的 则赋值给node节点 跳出循环
                    else {
                        do {
                            if (e.hash == hash &&
                                ((k = e.key) == key ||
                                 (key != null && key.equals(k)))) {
                                node = e;
                                break;
                            }
                            // 记录下匹配成功前一个节点
                            p = e;
                        } while ((e = e.next) != null);
                    }e
                }
                // 如果node不为空 则key匹配到node节点 !matchValue不匹配值 直接删除
                if (node != null && (!matchValue || (v = node.value) == value ||
                                     (value != null && value.equals(v)))) {
                    // 如果节点是红黑树节点 则直接删除节点
                    if (node instanceof TreeNode)
                        ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
                    // 如果 匹配的是p节点  就是 first node节点  直接将指针指向next节点
                    else if (node == p)
                        tab[index] = node.next;
                    // p是匹配成功节点的前一个节点 则直接将p的next指向 node的next节点
                    else
                        p.next = node.next;
                    ++modCount;
                    --size;
                    // 直接删除 视图操作
                    afterNodeRemoval(node);
                    // 返回删除的节点
                    return node;
                }
            }
            return null;
        }

     再看一下扩容操作是怎么样的。

     final Node<K,V>[] resize() {
            // 记录旧的table
            Node<K,V>[] oldTab = table;
            // 旧table 数组长度
            int oldCap = (oldTab == null) ? 0 : oldTab.length;
            // 旧的扩容点
            int oldThr = threshold;
            int newCap, newThr = 0;
            // 如果旧的容量大于0 且大于> 1<<30 则将threshold = 0x7fffffff
            if (oldCap > 0) {
                if (oldCap >= MAXIMUM_CAPACITY) {
                    threshold = Integer.MAX_VALUE;
                    return oldTab;
                }
                //左移1(oldCap*2)小于0x7fffffff 且 大于 16 newCap=oldThr*2
                else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                         oldCap >= DEFAULT_INITIAL_CAPACITY)
                    newThr = oldThr << 1; // double threshold
            }
            // newCap = 旧threshold
            else if (oldThr > 0) // initial capacity was placed in threshold
                newCap = oldThr;
            // 新容量 newCap= 16 新扩容点newThr= 16*0.75
            else {               // zero initial threshold signifies using defaults
                newCap = DEFAULT_INITIAL_CAPACITY;
                newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
            }
            // 如果 新的扩容点=0   新扩容点newThr= 16*0.75 如果大于 0x7fffffff 则设置为  0x7fffffff
            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"})
                 // 新建一个容量为   newCap 的node数组
                Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
            // 赋予当前table
            table = newTab;
            if (oldTab != null) {
                // 循环遍历旧的table
                for (int j = 0; j < oldCap; ++j) {
                    // first节点
                    Node<K,V> e;
                    if ((e = oldTab[j]) != null) {
                        // 设置为null
                        oldTab[j] = null;
                        // 如果只有first节点 直接设置到 新的tab[对hash取模]
                        if (e.next == null)
                            newTab[e.hash & (newCap - 1)] = e;
                        // 转换为红黑树扩容
                        else if (e instanceof TreeNode)
                            ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                        // 连接节点扩容
                        else { // preserve order
                            //   高位为0   头 loHead 尾 loTail
                            Node<K,V> loHead = null, loTail = null;
                            //   高位为1 存储在index+oldCap节点   头 hiHead 尾 hiTail
                            Node<K,V> hiHead = null, hiTail = null;
                            Node<K,V> next;
                            //循环遍历每个节点 直到链表尾部
                            do {
                                next = e.next;
                                /***
                                 *  e.hash & oldCap 这操作是取高位  oldCap总是2的倍数 即是 10000..... 取与则是最高位
                                 *  如果最高为0 扩容后 oldCap*2 & e.hash 值还是还是等于原来的,避免重新hash优化
                                 */
                                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);
                            // 如果不为空 直接在 table[j] 赋值链表
                            if (loTail != null) {
                                loTail.next = null;
                                newTab[j] = loHead;
                            }
                            // 如果不为空  赋值到 table[j+oldCap] 赋值链表
                            if (hiTail != null) {
                                hiTail.next = null;
                                newTab[j + oldCap] = hiHead;
                            }
                        }
                    }
                }
            }
            return newTab;
        }

    jdk8 同时提供了一些 类似 computeIfAbsent,foreach()等支持函数式接口入参,简化代码。下面列举两个例子。

       @Override
        // 提供的遍历的方式  BiConsumer 是jdk8提供的函数式接口 接受两个参数消费 无返回值
        public void forEach(BiConsumer<? super K, ? super V> action) {
            Node<K,V>[] tab;
            if (action == null)
                throw new NullPointerException();
            // 还是遍历table 通过 BigConsumer函数式接口入参
            if (size > 0 && (tab = table) != null) {
                int mc = modCount;
                for (int i = 0; i < tab.length; ++i) {
                    for (Node<K,V> e = tab[i]; e != null; e = e.next)
                        action.accept(e.key, e.value);
                }
                // 遍历时候不需要操作 如果操作抛出异常
                if (modCount != mc)
                    throw new ConcurrentModificationException();
            }
        }
      @Override
        // 查询某个key,如果不存在则调用 Function接口 apply(key) 获取value 再put到map中返回。
        public V computeIfAbsent(K key,
                                 Function<? super K, ? extends V> mappingFunction) {
            if (mappingFunction == null)
                throw new NullPointerException();
            int hash = hash(key);
            Node<K,V>[] tab; Node<K,V> first; int n, i;
            int binCount = 0;
            TreeNode<K,V> t = null;
            Node<K,V> old = null;
            // 查询map中是否存在key
            if (size > threshold || (tab = table) == null ||
                (n = tab.length) == 0)
                n = (tab = resize()).length;
            if ((first = tab[i = (n - 1) & hash]) != null) {
                if (first instanceof TreeNode)
                    old = (t = (TreeNode<K,V>)first).getTreeNode(hash, key);
                else {
                    Node<K,V> e = first; K k;
                    do {
                        if (e.hash == hash &&
                            ((k = e.key) == key || (key != null && key.equals(k)))) {
                            old = e;
                            break;
                        }
                        ++binCount;
                    } while ((e = e.next) != null);
                }
                V oldValue;
                // 如果存在则返回旧的value
                if (old != null && (oldValue = old.value) != null) {
                    afterNodeAccess(old);
                    return oldValue;
                }
            }
            // 调用 function 获取新的value
            V v = mappingFunction.apply(key);
            if (v == null) {
                return null;
            } else if (old != null) {
                // 设置新的值
                old.value = v;
                afterNodeAccess(old);
                return v;
            }
            else if (t != null)
                // 设置新的值
                t.putTreeVal(this, tab, hash, key, v);
            else {
                tab[i] = newNode(hash, key, v, first);
                if (binCount >= TREEIFY_THRESHOLD - 1)
                    treeifyBin(tab, hash);
            }
            ++modCount;
            ++size;
            afterNodeInsertion(true);
            return v;
        }

    具体红黑树操作有兴趣的同学可以自行去了解。

  • 相关阅读:
    PYTOHN1.day14
    PYTHON1.day13
    PYTHON1.day12
    PYTHON1.day11(n)
    PYTHON1.day10
    PYTHON1.day09
    PYTHON1.day08
    同步代码块 synchronized
    守护线程
    休眠线程
  • 原文地址:https://www.cnblogs.com/1ssqq1lxr/p/9528229.html
Copyright © 2011-2022 走看看