HashMap的源码分析(初始化情况、扩容的情况)(构造方法)

  HashMap<String, Integer> map = new HashMap<>();
  map.put("zs", 18);

按照初始情况来分析

class HashMap{
    
    
    
     transient Node<K,V>[] table;// Hashmap的底层数组
    
     int threshold;// 阈值(数组初始长度 * 加载因子) 
     //(数组初始长度16,加载因子0.75,则阈值12)(数组初始长度32,加载因子1,则阈值32)
     static final float DEFAULT_LOAD_FACTOR = 0.75f;
     final float loadFactor;// 加载因子 默认0.75
     static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // 默认的初始容量16
   
    //构造方法中没有对数组进行初始化,一定在第一次添加的时候进行初始化
    public HashMap() {
    
    
        this.loadFactor = DEFAULT_LOAD_FACTOR; 
    }
    
    
    
    static final int hash(Object key) {
    
    
        int h = 0;
        //  (h = key.hashCode()) ^ (h >>> 16);
        // 让高位右移,和低位异或(高位也起作用,充分散列)
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }
    
    // 添加方法    "zs"
    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) {
    
    
        
        // hash  : key经过计算hash值
        // key
        // value
        
        
        Node<K,V>[] tab;
        Node<K,V> p;
        int n, i;
        
        // table : // Hashmap的底层数组
        // tab = table == null: 真    构造方法中没有对数组初始化
        if ((tab = table) == null || (n = tab.length) == 0)
            
            // resize(): 扩容方法
            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;
        //添加过程大于阈值12就要扩容
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }
    
    
    
    
    final Node<K,V>[] resize() {
    
    
        
        // oldTab = table === null
        Node<K,V>[] oldTab = table;
        
        // oldCap = 0    旧容量
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        
        // threshold = 0 阈值(没有初始化)
        // oldThr  = 0
        int oldThr = threshold;
        
        int newCap, newThr = 0;		//定义新容量、新阈值
        
        //不大于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
            // 
            // DEFAULT_INITIAL_CAPACITY = 16
            // 新容量newCap = 16
            newCap = DEFAULT_INITI  AL_CAPACITY;
            // 新阈值newThr = 16 * 0.75 = 12
            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 = 12
        threshold = newThr;  
        // 创建一个长度为16 的数组
        Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
        
        //  hashmap的底层数组, 变成一个长度为16 的数组(这里就说明了数组的默认初始容量为16)
        //TIME : 16:22
        //接着分析扩容问题
        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;
    }

    
}

按照扩容的情况来分析 resize()

class HashMap{
    
    
    
    static final int MAXIMUM_CAPACITY = 1 << 30;
    
      
    // 在数组超过阈值扩容: 假如底层数组长度为16情况
    final Node<K,V>[] resize() {
    
    
        
        
        Node<K,V>[] oldTab = table;
        // oldCap = oldTab.length = 16
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        // 阈值oldThr = 12
        int oldThr = threshold;
        
        int newCap, newThr = 0;
        
        
        if (oldCap > 0) {
    
    
            //不大于1 << 30
            if (oldCap >= MAXIMUM_CAPACITY) {
    
    
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            
            //执行的是这里
            // newCap = 2 oldCap ---> 新容量= 旧容量* 2
       else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                // newThr = 12 * 2 = 24
                newThr = oldThr << 1; // double threshold
        }
        //else if和else就不会执行了
        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 = 24,阈值变24了
        threshold = newThr;
        // 创建一个长度为32的数组,赋给底层的table
        Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
        table = newTab;		//说明了:数组扩容(默认扩为原来的2倍)
        
        //至此,数组初始容量和扩容问题分析完了
        
        //接下来,看第2个构造方法(文件Demo3)
        
        
        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;
    }
    
    
}

构造方法2

class HashMap{
    
    
    
    
    public HashMap(int initialCapacity) {
    
    
        //调用下面的构造方法
        //                        0.75f(float类型)
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }
    
     public HashMap(int initialCapacity, float loadFactor) {
    
    
        //3个if是在做参数检验
        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;
         
        // initialCapacity = 14      
        // 初始长度为14
        // 给了threshold为16(),有点问题?对于这种初始化,resize()是一种新的情况,走的是新的逻辑
        // threshold = 16
        this.threshold = tableSizeFor(initialCapacity);// 不是很合理,没有用一个新定义的值记录:大于给定值的2个幂次(用阈值记录不合理)
    }
    
    //1000 --> 1111101000  	//cap = 1000
    
    // n |= n >>> 1;
    //  n =    1111100111		//n = cap - 1 
    //         0111110011		//n右移一位		>>>这个是无符号右移
    //  n =    1111110111		//或运算的结果(有一个为1则1)(区别于异或运算:不同则结果为1)
    
    
    //  n |= n >>> 2;
    //         0011111101
    //  n =    1111111111
    //        10000000000 -> 1024

    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 + 1    1024
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
    }
    
    
    
    
    
    //对于这种初始化,resize()是一种新的情况,走的是新的逻辑
    //新的扩容方式,来分析一下
    
    
     final Node<K,V>[] resize() {
    
    
        Node<K,V>[] oldTab = table;		//null
         //oldCap= 0		上面的初始化中只赋了2个值:
         //this.loadFactor = loadFactor;(0.75)
         //this.threshold = tableSizeFor(initialCapacity)(14到16)
         
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
         // oldThr = 16
        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 = 16 
            newCap = oldThr;
        else {
    
                   // zero initial threshold signifies using defaults
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
         
         
         
        //执行 
        if (newThr == 0) {
    
    
            // ft  = 16 * 0.75 = 12
            float ft = (float)newCap * loadFactor;
            // newThr = (int)ft = 12
            newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                      (int)ft : Integer.MAX_VALUE);
        }
         
        // threshold = 12
        threshold = newThr;
        // 创建一个长度为16 的数组
        Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
         
        //第2个构造方法讲完了
        //第3个构造方法不讲了(同样的道理)
         //第4个构造方法不讲了(同样的道理)
        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;
    }
    
}

猜你喜欢

转载自blog.csdn.net/AC_872767407/article/details/114681204