HashMap自动扩容机制源码详解

一、简介

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

往期回顾:

  • Java1.7的HashMap源码分析-面试必备技能

  • Java1.8的HashMap源码分析-面试必备技能

 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[] tab; Node 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 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)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[] resize() {
    Node[] 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[] newTab = (Node[])new Node[newCap];
    table = newTab;
    if (oldTab != null) {
        for (int j = 0; j < oldCap; ++j) {
            Node 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)e).split(this, newTab, j, oldCap);
                else { // preserve order
                    Node loHead = null, loTail = null;
                    Node hiHead = null, hiTail = null;
                    Node 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
  • 单个元素直接复制
  • 如果是树,调用树的复制方法
  • 如果是链表,循环链表复制

HashMap自动扩容机制源码详解_第1张图片

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

你可能感兴趣的:(HashMap自动扩容机制源码详解)