关于java:HashMap自动扩容机制源码详解

46次阅读

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

一、简介

  • HashMap 的源码咱们之前解读过,数组加链表,链表过长时裂变为红黑树。主动扩容机制没细说,明天具体看一下

二、扩容机制

先说论断:

  • hashmap 的容量都是 2 的倍数,比方 2,4,8,16,32,64 …
  • 每次扩容都是扩一倍,2 到 4,4 到 8,8 到 16,16 到 32 等等
  • 扩容因子:默认是 0.75,也能够指定一个小数
  • 扩容工夫点:当容器内的元素数量达到:容量 * 扩容因子 开始扩容

三、源码剖析

(1)先看构造函数

static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
static final float DEFAULT_LOAD_FACTOR = 0.75f;

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

默认的构造函数指定了扩容因子:0.75, 默认容量是 16

public HashMap(int initialCapacity) {this(initialCapacity, DEFAULT_LOAD_FACTOR);
}

指定初始容量,默认扩容因子:0.75

public HashMap(int initialCapacity, float loadFactor) {if (initialCapacity < 0)
        throw new IllegalArgumentException("Illegal initial capacity:" +
                                            initialCapacity);
    if (initialCapacity > MAXIMUM_CAPACITY)
        initialCapacity = MAXIMUM_CAPACITY;
    if (loadFactor <= 0 || Float.isNaN(loadFactor))
        throw new IllegalArgumentException("Illegal load factor:" +
                                            loadFactor);
    this.loadFactor = loadFactor;
    this.threshold = tableSizeFor(initialCapacity);
}

同时指定初始容量和扩容因子

/**
    * The next size value at which to resize (capacity * load factor).
    *
    * @serial
    */
int threshold;
  • 留神这个变量:下一个要扩容的值,扩容容量,容量 * 扩容因子
  • 看这一句:this.threshold = tableSizeFor(initialCapacity);
/**
 * 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;
}
  • 这个办法是取给定值四舍五入之后的 2 的倍数,比方 3—->4 ,15->16, 27->32
  • 至此筹备工作就做好了,上面看 put 办法

(2)put 办法

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

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                boolean evict) {Node<K,V>[] tab; Node<K,V> p; int n, i;
    // ① 最开始 table 为 null, 调用 resize()办法
    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);
                    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;
    // ② 完结的时候判断容量是不是大于扩容容量,大于则调用 resize 办法
    if (++size > threshold)
        resize();
    afterNodeInsertion(evict);
    return null;
}
  • ① 最开始 table 为 null, 调用 resize()办法
  • ② 完结的时候判断容量是不是大于扩容容量,大于则调用 resize()办法
  • 看 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;
    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) {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;
}
  • 先剖析第一种状况:Map map = new HashMap();
  • 走最初一个分支 , 容量为 16,扩容容量为 12

    else {
      newCap = DEFAULT_INITIAL_CAPACITY;
      newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
    }
  • 剖析第二种状况:Map map = new HashMap(20);
  • 走第二个分支,后面剖析过,threshold = tableSizeFor(20) 为 32
  • 新容量 newcap = oldThr 为 32
// 容量
else if (oldThr > 0) // initial capacity was placed in threshold
        newCap = oldThr;
  • 新扩容容量 newThr = newCap * loadFactor 为 24
// 扩容容量
if (newThr == 0) {float ft = (float)newCap * loadFactor;
    newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                (int)ft : Integer.MAX_VALUE);
}
threshold = newThr;
  • 剖析第三种状况:下面的 map 曾经插入 24 个元素,新插入一个要扩容
  • 走第一个分支,oldCap=32,oldThr=24
  • 扩容:newCap = oldCap << 1 为 64
  • 扩扩容容量 newThr = oldThr << 1 为 48

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
}
  • 最初是复制元素到新的 table
  • 单个元素间接复制
  • 如果是树,调用树的复制办法
  • 如果是链表,循环链表复制

欢送关注微信公众号:丰极,更多技术学习分享。

正文完
 0