HashMap源码探究之构造方法

HashMap构造方法有四种,下面依次说一说(按照源码顺序)

1. 带容量大小和加载因子的构造方法

例如: Map<String,String> map01 = new HashMap<String,String>(5,0.5f);

	public HashMap(int initialCapacity, float loadFactor) {
    
    
		//1.判断容量是否小于0
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " +initialCapacity);
        //2.判断容量是否大于容量默认最大值(1 << 30,即2的30次方)
        if (initialCapacity > MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;
        //判断加载因子是否大于0
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal load factor: " + loadFactor);
        this.loadFactor = loadFactor;
        //由threshold字段储存容量大小
        this.threshold = tableSizeFor(initialCapacity);
    }
    /*这个方法是一着妙手,计算出大于等于参数的第一个二次方数,
    例如:1返回1,3返回4,8返回8,9返回16,125返回128,
    如果参数大于默认最大值,则容量取默认最大值。*/
    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. 仅带容量大小的构造方法

例如:Map<String,String> map02 = new HashMap<>(10);
调用第一个构造方法,主要是为了计算容量大小,和确定加载因子。

	public HashMap(int initialCapacity) {
    
    
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }
3.无参构造方法

例如:Map<String, String> map03 = new HashMap<>();
仅确定加载因子,所以可以看出来这是个懒加载

	public HashMap() {
    
    
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }
4. 带一个Map的构造方法

例如:Map<String,String> map04 = new HashMap<>(map02);
创建过程涉及到扩容,解释起来有点复杂,请翻阅我的另外一篇专讲HashMap扩容的博客。

	public HashMap(Map<? extends K, ? extends V> m) {
    
    
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        putMapEntries(m, false);
    }
    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;
                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);
            }
        }
    }

猜你喜欢

转载自blog.csdn.net/TreeCode/article/details/107971860