HashMap容量增长源码分析

   HashMap其实是通过一个线性数字Entry保存值的,默认构造方法的容量大小为16,当要添加值进去,容量到了当前容量的75%时,Entry容量会扩大一倍,以下是部分关键源码:
    static final float DEFAULT_LOAD_FACTOR = 0.75f;//默认负载系数
    static final int DEFAULT_INITIAL_CAPACITY = 16;//默认为16

    //无参构造方法
    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        threshold = (int)(DEFAULT_INITIAL_CAPACITY * DEFAULT_LOAD_FACTOR);//threshold 默认为12,当size超过threshold时,Entry数组会增大一倍
        table = new Entry[DEFAULT_INITIAL_CAPACITY];//Entry数组默认大小为16
        init();
    }

    //往HashMap中put一个值
    public V put(K key, V value) {
        if (key == null)
            return putForNullKey(value);
        int hash = hash(key.hashCode());
        int i = indexFor(hash, table.length);
        for (Entry<K,V> e = table[i]; e != null; e = e.next) {
            Object k;
            if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
                V oldValue = e.value;
                e.value = value;
                e.recordAccess(this);
                return oldValue;
            }
        }

        modCount++;
        addEntry(hash, key, value, i);//这里添加一个entry
        return null;
    }

    //添加一个Entry
    void addEntry(int hash, K key, V value, int bucketIndex) {
	Entry<K,V> e = table[bucketIndex];
        table[bucketIndex] = new Entry<K,V>(hash, key, value, e);
        if (size++ >= threshold)//当size超过threshold时,Entry数组会增大一倍
            //Entry数组容量扩大一倍,并且threshold=新的Entry数组容量*负载系数
            resize(2 * table.length);
    }

你可能感兴趣的:(HashMap)