美文网首页
HashMap小抄

HashMap小抄

作者: 上海马超23 | 来源:发表于2017-07-02 23:06 被阅读0次
public class HashMap {
  // 哈希桶数组
  transient Node<K,V>[] table;

  // 链表进化成红黑树的阈值
  static final int TREEIFY_THRESHOLD = 8;

  // 默认当桶里的Node数量达到容量的75%,哈希冲突已经严重
  // 会成倍扩容桶容量,并重新分配所有Node
  static final float DEFAULT_LOAD_FACTOR = 0.75f;

  // 默认容量是2的4次方,16
  static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; 
  
  // 参数hash是key的hash值
  final Node<K,V> getNode(int hash, Object key) {
        Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
        if ((tab = table) != null && (n = tab.length) > 0 &&
            // 当length即n为2的N次方时,hash&(length – 1)就相当于对length取模,而且速度比直接取模快得多,这是HashMap在速度上的一个优化
            // 因为length-1后所有位都变成了1,“与”操作后得出的结果,哪几位是1,就是取模的结果了
            // 通过key的hash取模桶数组的大小,得到数组的下标
            (first = tab[(n - 1) & hash]) != null) {
            if (first.hash == hash && // always check first node
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
            if ((e = first.next) != null) {
                // 可以看到java8里用红黑树结构作为桶了
                if (first instanceof TreeNode)
                    return ((TreeNode<K,V>)first).getTreeNode(hash, key);
                do {
                    // 链表结构的桶,遍历查找key
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;
    }

    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = 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);
                        // 桶里的Node数量超过阈值,改用红黑树加快key的查找速度
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            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);
        return null;
    }
  
  // 扩容
  final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table;
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        int oldThr = threshold;
        int newCap, newThr = 0;
        if (oldCap > 0) {
            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;
        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) {
            // 因为容量变化了,所有Node需要重新取模分配桶
            // 扩容成本不低,最好初始化预估好容量
            for (int j = 0; j < oldCap; ++j) {
                Node<K,V> e;
                if ((e = oldTab[j]) != null) {
                    oldTab[j] = null;
                    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
                        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;
    }

    // 保证容量始终是2的N次方,方便快速取模
    // 随便给一个初始值比如17会转为32
    static final int tableSizeFor(int cap) {
        int n = cap - 1;
        n |= n >>> 1;
        n |= n >>> 2;
        n |= n >>> 4;
        n |= n >>> 8;
        n |= n >>> 16;
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
    }
}

相关文章

  • HashMap小抄

  • 生信学习Day6-小白

    mark下小抄-搜索xx小抄-https://www.rstudio.com/resources/cheatshe...

  • 学习小组Day6笔记——四海

    学习R包 R包都有自己的说明书(cheatsheet),俗称小抄。 获取R包小抄的方法 百度XX小抄 找Rstud...

  • Day6-孟思博

    R包小抄的介绍: R包都有自己的说明书(cheatsheet),俗称小抄。在对包有了一定的了解后,小抄是一个很好的...

  • 小抄

    说到蒋介石就会想起宋美龄,但据说蒋最爱的女人叫陈洁如。蒋初见她则心动不已,对她进行疯狂追求,最后终于赢得美人归。他...

  • 小抄

  • 小抄

    何为孤寂? 清风、艳日、无笑意; 可否具体? 左拥、右抱、无情欲。 可...

  • 小抄

    早知道,这世上,更多的是南辕北辙,而不是殊途同归,以后是平庸还是惊世,是绚丽还是落魄。我都希望,在悲喜交织的岁月,...

  • 小抄

    我心中12岁的你,不是现实的你,你不过是一个假设。一切都是我想象的产物。你仍然保持着你的美丽、健康和聪敏,而且如今...

  • 小抄

    有关你的记忆会留下,你手掌的触感会留下,心灵的剧烈震撼会留下。期盼将你拥入怀中的渴望会留下。纵然我变成了另一个人,...

网友评论

      本文标题:HashMap小抄

      本文链接:https://www.haomeiwen.com/subject/cyyocxtx.html