HashMap的初始容量大小和长度扩展。hash算法

总结:

初始容量:默认16

加载因子:默认0.75.  map集合长度大于上一次扩展前长度1.75倍的时候再扩展。每次扩展都是原来的两倍。

先看构造方法。

 /**
     * The default initial capacity - MUST be a power of two.
        初始容量默认为16,扩展的时候也必须是2的次幂
     */
 static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

/**
 * The load factor used when none specified in constructor.
       默认的加载因子是0.75
 */
static final float DEFAULT_LOAD_FACTOR = 0.75f;
    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }
	
	public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }
	
	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);
    }
    public HashMap(Map<? extends K, ? extends V> m) {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        putMapEntries(m, false);
    }

 对应不同的构造

        HashMap map1=new HashMap();//不指定长度,默认扩展因子
        HashMap map2=new HashMap(10);//指定长度,默认扩展因子
        HashMap map3=new HashMap(10,0.7f);//指定长度和扩展因子
        HashMap map4=new HashMap(innermap);//长度根据innermap计算,默认扩展因子

加载因子

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

hash函数 计算对象在链表上的地址。

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

加载因子的触发时机

final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
    int s = m.size();
    if (s > 0) {
        if (table == null) { // pre-size
            float ft = ((float)s / loadFactor) + 1.0F;  //当map的长度大于0.75+1.0f上一次扩展后的长度后,map集合自动扩展
            int t = ((ft < (float)MAXIMUM_CAPACITY) ?
                     (int)ft : MAXIMUM_CAPACITY);
            if (t > threshold)
                threshold = tableSizeFor(t);
        }
        else if (s > threshold)
            resize();
        for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
            K key = e.getKey();
            V value = e.getValue();
            putVal(hash(key), key, value, false, evict);
        }
    }
}
/**
扩展以后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;
}
上一篇:Java 8 HashMap(一)—— 构造方法


下一篇:HashMap学习笔记(一)构造方法及重要属性