java HashMap 源码

内部数据结构

  • hashMap 底层是一个 Node 类型的数组,Node 是一个单链表。但是当哈希冲突导致同一个位置的单链表长度超过 8 时,单链表会转换成红黑树:TreeNode ,以提高冲突后的检索效率。(TreeNode 是 Node 的子类)。

    /**
     * The table, initialized on first use, and resized as
     * necessary. When allocated, length is always a power of two.
     * (We also tolerate length zero in some operations to allow
     * bootstrapping mechanics that are currently not needed.)
     */
    transient Node<K,V>[] table;
    
  • hashMap 内部数组的大小必须是 2 的乘方。原因在于 hashMap 根据键的哈希值定位对象在数组中的位置时采用的算法不是通过对数组长度取模而是采用位运算,这样能够极大提高计算性能。

    pos = (length - 1) & hash;
    

    要使得 pos 在[0 , length-1] 之间均匀分布,length -1 的值必须为全 1 即 111,1111,11111…,所以 length 必须为 2 的乘方。

初始化及扩容

  • hashMap 初始化时默认的容量为 16 。通过构造器指定初始值(或以已有的 Map)作为构造器参数时会将初始值修正为 2 的乘方,即大于指定初始值(或原有 Map 大小)的最小的 2 的乘方:

    /**
     * Returns a power of two size for the given target capacity.
     */
    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;
    }
    

    算法不直观比较难懂,可以拿几个具体的数试一下。结果就是从最高位开始全部补 1 变成形容 111,1111,1111… 的数,最后加一成为 2 的乘方。

  • hashMap 扩容策略为二倍扩容,即每次扩容后的数组长度是扩容前长度的二倍。而扩容发生的时机由装载因子(loadFactor)决定:当前容器中元素的个数 > 数组长度*装载因子 时发生扩容。

    if (++size > threshold)
    resize(); //扩容
    

    threshold 用于记录下次扩容时的元素数量,初始值为:初始数组长度*装载因子。每次扩容时 threshold 也会变为原来的二倍,所以 threshold 一直保持是当前数组长度*装载因子。

  • hashMap 扩容代价相比于 ArrayList 的代价要高的,这也是为什么使用 haspMap 及 HashSet 是尽量指定初始大小的原因。

    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) {  //超过最大容量无法继续扩容,do nothing。
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1;   //数组长度和下次扩容数量都二倍增长
        }
        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) {  //扩容后开始迁移数据
            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);  //单链表元素超过 8 个成为红黑树,此时需要对红黑树进行拆分然后放入对应的位置
                    else {    //单链表有多个元素,此时有些元素需要调整位置而有些不需要
                        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;
    }
    
    //扩容过程中对红黑树的拆分操作
    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;
                }
            }
    
            if (loHead != null) { //放在原位置的元素链表
                if (lc <= UNTREEIFY_THRESHOLD)
                    tab[index] = loHead.untreeify(map); //将红黑树转换成单链表
                else {
                    tab[index] = loHead;
                    if (hiHead != null) // (else is already treeified)
                        loHead.treeify(tab); //hiHead 不为空说明红黑树中元素减少,需要重构红黑树
                }
            }
            if (hiHead != null) { //需要调整位置的元素链表
                if (hc <= UNTREEIFY_THRESHOLD)
                    tab[index + bit] = hiHead.untreeify(map); //红黑树转换为单链表
                else {
                    tab[index + bit] = hiHead;
                    if (loHead != null)
                        hiHead.treeify(tab); //lohead 不为空说明红黑树中元素减少,需要重构红黑树
                }
            }
        }
    

put 操作

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)  //只有在第一次进行 put 操作时才会分配数组的内存空间
            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)))) //元素所在位置不为空且 key 相同
                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);
                        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)))) //链表中已有相同 key 的元素
                        break;
                    p = e;
                }
            }
            if (e != null) { // 已存在相同 key 的元素 
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value; //用新的value 替换旧的 value
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值