关于java:HashMap源码分析Java8

3次阅读

共计 7292 个字符,预计需要花费 19 分钟才能阅读完成。

前言

HashMap 属于陈词滥调的话题,离上一次浏览源码曾经很久了,为了避免我又双叒遗记一些实现细节决定写篇文章,温故而知新

首先从结构 HashMap 说起,

    public HashMap() {this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted}

loadFactor 为负载系数默认 0.75,用于计算 Map 扩容的阈值

我画了一下 HashMap 大抵的数据结构,图中右边红色即为 HashMap 的 table 表,实际上就是一个 Node 的数组

Node<K,V>[] table;

Node 的构造很简略,罕用的表白单项链表的数据结构

    static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        V value;
        Node<K,V> next;

插入 put

一次插入操作实际上就是计算插入 key 的 hash 值并落到具体的 table 数组的某个下标,在通过下标找到 table 上的 head,在通过链表 (或者红黑树) 进行插入,如果该链表 (或者树) 已存在则对链表尾端进行插入操作,上面开始具体阐明具体的实现细节

以一次一般 put 操作为例

    public V put(K key, V value) {return putVal(hash(key), key, value, false, true);
    }

put 操作并没有间接应用 key 自带的 hash,而是通过 hash()做一层转换

   static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }
hash

key 为空则将 hash 设置为 0, 也意味着所有 key 为 null 的数据最初都固定寄存在 table[0]中 (多说一句,table[0] 并不是只寄存 key 为 null 的 node)

h = key.hashCode()) ^ (h >>> 16) // 计算 hashcode

这里将 key 的 hashcode 码与本人的右移 16 位 (行将 32 位中的高 16 位偏移到低 16 位) 做按 位异或 运算。

为什么要这么做呢? 次要是减小后续取模的碰撞概率而做的优化

能够参考这篇文章,大抵意思就是因为取模运算只关注低位,如果 hash 低位同一性高会增大碰撞概率, 所以将高位做右移并做异或减少低位的随机性。

下图示意在掩码为 9 位应用 HashMap.hash(table 长度 512)时比 hashCode 碰撞次数小百分之 10

另外你会常常看到通过 (n – 1) & hash 这种形式获取以后 hash 值对应 table 数组下标的操作,其中 n 为 table 数组

其实原理很简略,首先 hashmap 会保障 table 的长度肯定为 2 的整数幂,上面以一个 table 长度为 128 的数组为例

当对 table 的长度 n 减 1 时,因为只有高位一个 1 所以其余全副置为 1

所以当减 1 后的 table 与 hash 做与操作时,后果必然是 table 数组下某个下标,并保障其散布。

插入

查看 table 为空则扩容 (扩容上面会讲到),新的值没有对应的槽时创立新的 Node,否则便插入已存在的链表(树) 中,细节能够看下我为源码做的注解

    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;
        // p 即为 table 上头节点
        if ((p = tab[i = (n - 1) & hash]) == null)
            // 未找到槽则创立新的 node 作为头节点
            tab[i] = newNode(hash, key, value, null);
        else {
            // 插入已存在的链表中
            ...
        }
        // 记录批改次数,用于迭代校验
        ++modCount;
        //size 超出阈值则扩容
        if (++size > threshold)
            resize();
        // 用于 linked 类型 map,hashmap 未实现
        afterNodeInsertion(evict);
        return null;

插入已存在的链表 (树) 中,当呈现 hash 碰撞 (collision) 时,即以后 key 的 hash 所对应的 table 中的 node 已存在时,hashmap 会依据 key 的状况 (有无反复) 来抉择是插入链表尾部还是替换链表中某个 node 的值

    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;
            // p 为 table 上的头节点
            // 如果雷同 key,将 p 赋值给 e,e 示意已存在值为 key 的 node
            // 独自校验头节点是为了不便间接替换,防止判断是否为红黑树或链表
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            // 头节点 node 为红黑树时
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {for (int binCount = 0; ; ++binCount) {
                    // 遍历至链表的尾端 e 为被标记的反复 key 的 node
                    if ((e = p.next) == null) {p.next = newNode(hash, key, value, null);
                        // 链表长度超过 8 个转换为树
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st            // 当链表长度大于等于 8 并且 tab 长度大于 64 时才会转为红黑树
                            treeifyBin(tab, hash);
                        break;
                    }
                    // 发现雷同的 key 则标记
                    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;
                //onlyIfAbsent 为 False 则替换
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                // 用于预留给其余 Map 预留的刷新拜访程序接口,例如 LinkedHashMap assessOrder 指定为 true 时会将最新插入的 node 移至链表尾部
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        // 超出阈值 resize
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

须要留神的几点

  • 判断 key 是否反复须要满足对象地址雷同 (==) 或者 equals 是否相等(equals())
  • 并不时说链表长度超出阈值 (阈值为 8) 就会转为红黑树,同时还要满足以后 hashmap 的 table 长度大于 64,否则只会做一次 resize 操作

resize

在 hashap 初始化时,或者 table 长度超过阈值等状况时,会对 hashmap 做 resize 操作,个别会对 table*2,table 指定为 2 的倍数是为了不便做求模的计算,非凡状况比方 table 长度超过 2^30 时,则将阈值固定为 2^31- 1 并间接返回

    final Node<K,V>[] resize() {Node<K,V>[] oldTab = table;// 旧的 table 长度
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        int oldThr = threshold;~~~~
        int newCap, newThr = 0;
        //oldCap 大于 0 调整 threshold 阈值
        if (oldCap > 0) {
            // 超过 2^30 threshold 阈值设为 2^31
            // 设置为 2^30 是为了避免后续扩容操作溢出
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            // 这里对 newCap 扩容一倍
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; // double threshold
        }
        // 容量为 0 时 newCap 大小取决于阈值 threshold 的设置
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;
        // 阈值 threshold 以及 capacity 都为初始状态是启用默认设置
        else {               // zero initial threshold signifies using defaults
            // 阈值未设置并 cap 为 0 的状况(初始化状态)
            newCap = DEFAULT_INITIAL_CAPACITY;// 默认 16
            // 初始化阈值 12
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
        // 依据 newCap 调配 newThr
        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) {
            // 遍历旧 talble 上的每个 node
            for (int j = 0; j < oldCap; ++j) {
                Node<K,V> e;
                if ((e = oldTab[j]) != null) {oldTab[j] = null;
                    if (e.next == null)
                        //e.hash & (newCap-1) -1 当 newCap 保障为 2 的 n 次幂时等同取模操作
                        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;//loHead 代表旧的索引地位
                        Node<K,V> hiHead = null, hiTail = null;//hiHead 代表扩容后新的索引地位
                        Node<K,V> next;
                        do {
                            next = e.next;
                         
 
 // 索引地位为 cap & hashcode 扩容后索引是否有变动取决于 hashcode&cap 的位是否为 1 概率上有一半的 entry 须要挪动
 
                            if ((e.hash & oldCap) == 0) {// 为 0 示意该 node 不须要挪动 table 索引地位
                                if (loTail == null)
                                    loHead = e;// 首次增加设置链表头
                                else
                                    loTail.next = e;
                                loTail = e;
                            }
                            else {//e.hash & oldCap 为 1 搁置到新的链表上
                                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;
                            // 设置扩容后须要挪动的索引,新链表搁置到 j +oldCap             
                            newTab[j + oldCap] = hiHead;

                        }
                    }
                }
            }
        }
        return newTab;
    }

扩容后的调配:创立扩容后 newTab 后,接下来是重新分配原有的 Node 至 newTable 上,过程并不简单,首先是遍历原先的 oldTable 数组

if (oldTab != null) {for (int j = 0; j < oldCap; ++j) {...}~~~~

首先获取每个数组元素下 (bins) 的头节点,如果头节点 node 的 next 为空间接将该 node 调配至新的 newTable 下,如果该元素下的链表由多个组成的话则遍历该链表,依据以后 Node 的 hash 值与原有数组长度 oldCap 的与运算后果来决定调配是否调配到新的 bins 下。比方上面的示例,同一个 bins 下的 hashcode 只能保障 oldCap- 1 的 & 雷同,所以链表中的 node 被重新分配的概率为 1 /2,即链表中有一半的 node 将会重新分配。

1111 0000 0010 1001 0101 1101 1011 1011 hashcode
0000 0000 0000 0000 0000 0000 0001 0000 16 为 oldCap
0000 0000 0000 0000 0000 0000 0010 0000 32 为 newCap

Map.get

get 绝对就比较简单了,get(key)外部调用了 getNode 并传递了 key 的 hashcode,做法也很简略,获取到该 key 所对应再 table 中的第一个 node,如果是链表就遍历链表获取 value,红黑树则做树的查找操作

    final Node<K,V> getNode(int hash, Object key) {Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
        // 满足三个条件 1. table 不为空 2. table 长度大于 0 3. 以后 hash 的对应的索引 node 不为空
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (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) {
                // 从树中查找
                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);
            }
        }
        return null;
    }

// 红黑树

LinkdedHashMap

LinkedHashMap 继承于 HashMap,其大部分实现是统一的,那么它是通过什么形式保障有序的呢?
首先 LinkedHashMap 重写了 HashMap 的 newNode 办法

    Node<K,V> newNode(int hash, K key, V value, Node<K,V> e) {      
        //LinkedHashMap.Entry 继承 Node 类
        LinkedHashMap.Entry<K,V> p =
            new LinkedHashMap.Entry<K,V>(hash, key, value, e);      
        // 将新增的 node 增加至链表尾部
        linkNodeLast(p);
        return p;
    }

LinkedHashMap.Entry 继承 Node 类

    static class Entry<K,V> extends HashMap.Node<K,V> {
        Entry<K,V> before, after;
        Entry(int hash, K key, V value, Node<K,V> next) {super(hash, key, value, next);
        }
    }

Entry 相比 Node 多保护了向前和向后的援用,也就是 LinkedHashMap 相比 HashMap 多保护了一个双向链表来满足依照程序迭代的需要,每次插入会将 Node 插入链表尾部。

前面的就很好了解了,Map 的遍历是基于迭代器的设计模式,LinkedHashMap 从新实现了 Iterator 接口

    final class LinkedEntryIterator extends LinkedHashIterator
        implements Iterator<Map.Entry<K,V>> {public final Map.Entry<K,V> next() {return nextNode(); }
    }

不言而喻,nextNode 理论就是获取链表中的下一个节点

        final LinkedHashMap.Entry<K,V> nextNode() {
            LinkedHashMap.Entry<K,V> e = next;
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            if (e == null)
                throw new NoSuchElementException();
            current = e;
            next = e.after;
            return e;
        }

另外 LinkedHashMap 能够通过 assessOrder 指定新增 Node 移至尾部,感兴趣的能够看看源码实现比较简单。

正文完
 0