HashMap源码分析(容量与初始化)

一、成员属性

1、transient HashMapInit.Node<K,V>[] table;

元素容器,是一个数组,其中的元素是一个链表或树

capacity最大MAXIMUM_CAPACITY

可容纳的元素总数受loadFactor限制,元素总数达到loadFactor时就扩容

初始化如果提供了容量参数,

threshold为capacity的最小2次幂,

第一次添加元素时初始化table,capacity=threshold

默认为16,最大为MAXIMUM_CAPACITY,永远都是2的次幂,

优点是,这个长度的数组,最大的下标是capacity-1,二进制后面都是1,落槽快

列表形态是Node,树形态为Node的子类TreeNode

注意:

capacity,threshold达到极限后,依然可以添加元素,不会出错,但内存容量有限

 

2、transient Set<Entry<K,V>> entrySet;

缓存entrySet

3、transient int size;

当前元素个数

4、transient int modCount;

变更次数

5、int threshold;

临界值,如果size达到了临界值,就扩容,最大值为integer.max

这个值不会溢出,因为threshold溢出,capacity比如已经溢出了

除了有参构造,初始化threshold为capacity的最小2次幂,

capacity<MAXIMUM_CAPACITY时,threshold=capacity*loadFactor

capacity>=MAXIMUM_CAPACITY时,threshold=capacity*loadFactor或integer.max

有参构造时,

初始化指定容量和负载因子时为capacity的最小2次幂,

第一次添加元素时作为了capacity

无参构造时,

初始化阶段capacity和threshold都是0,

第一次添加元素capacity为16,threshold=capacity*loadFactor

注意:

capacity,threshold达到极限后,依然可以添加元素,不会出错,但内存容量有限

6、final float loadFactor;

hash的负载因子默认0.75f

这个值就用了一次,

如果是有参构造,在第一次初始化时threshold=capacity*loadFactor

后面threshold都是<<1

 

注意:这里称桶的长度叫容量capacity,最大元素数量叫临界值

 

7、tableSizeFor讲解

/**
     * 为给定的目标容量返回两个大小的幂
     * 最终结果就是,cap二进制为1的最高位后面全部变成1,最后+1,就变成了最高位表示的数*2
     * 有参构造时调用一次,初始化threshold为比cap大的最小2次幂
     * 第一次添加元素进行扩容时,capaCity=oldThreshold;newThreshold=capaCity*loadFactor
     */
    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;
    }

 

二、构造方法,初始化

HashMap在构造时,默认情况下不会初始化table,

无参构造只设置负载因子,第一次添加元素为设置容量为16,临界值为16*0.74

有参构造,指定初始化容量和负载因子,默认初始化容量为大于容量的最小2次幂,后面在已*负载因子为准

有参构造,指定初始化容量,则默认负载因子为0.75,然后调用上一个有参构造

三、源码分析

    /**
     * 默认容量是16
     */
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

    /**
     * 最大容量1 << 30;2的30幂(最高位没有用),桶的最大长度
     */
    static final int MAXIMUM_CAPACITY = 1 << 30;

    /**
     * 默认负载因子
     */
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

    /**
     * 列表转树的阀值
     */
    static final int TREEIFY_THRESHOLD = 8;

    /**
     * 树转列表的阀值
     */
    static final int UNTREEIFY_THRESHOLD = 6;

    /**
     * 最小数容量,数的元素太多就要调整表
     */
    static final int MIN_TREEIFY_CAPACITY = 64;

    /**
     * node,有四个值,hash,key,value,next
     * TreeNode是Node的子类,数形态
     */
    static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        V value;
        HashMapInit.Node<K,V> next;

        Node(int hash, K key, V value, HashMapInit.Node<K,V> next) {
            this.hash = hash;
            this.key = key;
            this.value = value;
            this.next = next;
        }

        public final K getKey()        { return key; }
        public final V getValue()      { return value; }
        public final String toString() { return key + "=" + value; }

        public final int hashCode() {
            return Objects.hashCode(key) ^ Objects.hashCode(value);
        }

        public final V setValue(V newValue) {
            V oldValue = value;
            value = newValue;
            return oldValue;
        }

        public final boolean equals(Object o) {
            if (o == this)
                return true;
            if (o instanceof Map.Entry) {
                Map.Entry<?,?> e = (Map.Entry<?,?>)o;
                if (Objects.equals(key, e.getKey()) &&
                        Objects.equals(value, e.getValue()))
                    return true;
            }
            return false;
        }
    }

    /* ---------------- Static utilities -------------- */

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



    /**
     * 为给定的目标容量返回两个大小的幂
     * 最终结果就是,cap二进制为1的最高位后面全部变成1,最后+1,就变成了最高位表示的数*2
     * 有参构造时调用一次,初始化threshold为比cap大的最小2次幂
     * 第一次添加元素进行扩容时,capaCity=oldThreshold;newThreshold=capaCity*loadFactor
     */
    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;
    }

    /* ---------------- Fields -------------- */

    /**
     * 元素容器,是一个数组,其中的元素是一个链表或树
     * capacity最大MAXIMUM_CAPACITY
     * 可容纳的元素总数受loadFactor限制,元素总数达到loadFactor时就扩容
     * 初始化如果提供了容量参数,
     *      threshold为capacity的最小2次幂,
     *      第一次添加元素时初始化table,capacity=threshold
     * 默认为16,最大为MAXIMUM_CAPACITY,永远都是2的次幂,
     *      优点是,这个长度的数组,最大的下标是capacity-1,二进制后面都是1,落槽快
     * 列表形态是Node,树形态为Node的子类TreeNode
     * 注意:
     *  capacity,threshold达到极限后,依然可以添加元素,不会出错,但内存容量有限
     */
    transient HashMapInit.Node<K,V>[] table;

    /**
     * 缓存entrySet
     */
    transient Set<Entry<K,V>> entrySet;

    /**
     * 当前元素个数
     */
    transient int size;

    /**
     * 变更次数
     */
    transient int modCount;

    /**
     * 临界值,如果size达到了临界值,就扩容,最大值为integer.max
     * 这个值不会溢出,因为threshold溢出,capacity比如已经溢出了
     * 除了有参构造,初始化threshold为capacity的最小2次幂,
     * capacity<MAXIMUM_CAPACITY时,threshold=capacity*loadFactor
     * capacity>=MAXIMUM_CAPACITY时,threshold=capacity*loadFactor或integer.max
     * 有参构造时,
     *      初始化指定容量和负载因子时为capacity的最小2次幂,
     *      第一次添加元素时作为了capacity
     * 无参构造时,
     *      初始化阶段capacity和threshold都是0,
     *      第一次添加元素capacity为16,threshold=capacity*loadFactor
     *  注意:
     *      capacity,threshold达到极限后,依然可以添加元素,不会出错,但内存容量有限
     * @serial
     */
    int threshold;

    /**
     * hash的负载因子默认0.75f
     * 这个值就用了一次,
     * 如果是有参构造,在第一次初始化时threshold=capacity*loadFactor
     * 后面threshold都是<<1
     * @serial
     */
    final float loadFactor;

    /* ---------------- Public operations -------------- */

    /**
     * 不初始化table
     * 负载因子使用默认值或用户提供的值
     * threshold为initCapacity的最小2次幂,
     * 第一次添加元素扩容时,newCap=oldThr, oldThr=newCap*loadFactor,
     */
    public HashMapInit(int initialCapacity, float loadFactor) {
        if (initialCapacity < 0)//非法初始化容量
            throw new IllegalArgumentException("Illegal initial capacity: " +
                    initialCapacity);
        if (initialCapacity > MAXIMUM_CAPACITY)//超出就设置为1<<30;
            initialCapacity = MAXIMUM_CAPACITY;
        if (loadFactor <= 0 || Float.isNaN(loadFactor))//负载因子不能小于等于0,不能不是数
            throw new IllegalArgumentException("Illegal load factor: " +
                    loadFactor);
        this.loadFactor = loadFactor;
        this.threshold = tableSizeFor(initialCapacity);
    }

    /**
     * 不初始化table
     * 负载因子使用默认值,
     * capacity和threshold都是系统默认值0
     * 第一次添加元素扩容时,newCap=16,newThr=newCap*loadFactor
     * @param initialCapacity
     */
    public HashMapInit(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }

    public HashMapInit() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }

    /**
     * hash(key)=(key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16)
     */
    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) {
        //tab为桶数组,p为目标桶,n为桶容量(长度),i为目标桶的下标
        HashMapInit.Node<K,V>[] tab; HashMapInit.Node<K,V> p; int n, i;
        //如果table为null或者长度为0,进行扩容
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        //n-1是一个二进制位后面全是1的数,&上hash就是取余。i就是要插入的元素所在的桶
        //如果目标桶是空的就新建一个node,放到table[i]
        //数组是从0开始的,n-1就是最大的下标
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {//如果不为空
            //k为目标桶第一个元素的key,
            //key一样的时候,e就是一家存在的那个key对应的node
            HashMapInit.Node<K,V> e; K k;
            //  先和目标桶的首元素进行比较
            // 如果要插入的元素的hash和目标同桶首元素的hash相等,key也相等,就把p赋值给e。
            if (p.hash == hash &&
                    ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
                //如果是一个树,就按树的方式去插入元素
            else if (p instanceof HashMapInit.TreeNode)
                e = ((HashMapInit.TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {//如果不是树,进行遍历,遇到hash和key一样的就替换,或者在最后一个元素的末尾追加
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        //如果bincount>7,那么现在就到达了8个,需要列表转树
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    //如果key一样
                    if (e.hash == hash &&
                            ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            //如果key已经存在,e是已经存在的那个node,更新node的value
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                //onlyIfAbsent是一个条件,
                // 如果onlyIfAbsent为false,直接赋值
                // 如果onlyIfAbsent为true,oldValue为null也赋值
                // 如果onlyIfAbsent为true,oldValue不是null就不赋值
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;//修改次数
        //如果数量超过了临界值就扩容
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);//回调,先不用不管
        return null;
    }

    /**
     * 扩容
     * 第一次添加元素进行扩容(threshold就已经定型了,永远都是capaCity*loadFactor)
     *  无参构造:newCap=16,newThr=newCap*loadFactor
     *  有参构造:oldThr= 大于initCap的最小2次幂,newCap=oldThr, oldThr=newCap*loadFactor,
     *
     * 其他情况下的扩容
     *  newCap= (oldCap < MAXIMUM_CAPACITY) ? oldCap<1 : oldCap
     *  newThr = (oldCap < MAXIMUM_CAPACITY) ? oldThr<1 : Integer.MAX_VALUE;
     *  同样newThr = (oldCap < MAXIMUM_CAPACITY) ? oldCap*loadFactor : Integer.MAX_VALUE;
     * @return the table
     */
    final HashMapInit.Node<K,V>[] resize() {
        HashMapInit.Node<K,V>[] oldTab = table;
        int oldCap = (oldTab == null) ? 0 : oldTab.length;//旧的桶长度
        int oldThr = threshold;//旧的临界值
        int newCap, newThr = 0;
        //oldCap > 0说明这已经不是第一次添加元素了,已经扩容过一次
        if (oldCap > 0) {//如果现在的长度大于0,table必然已经经历过初始化了
            //如果桶的长度已经大于1<<30,则临界值设置为最大MAX_VALUE。不能在进行扩容了
            //说明,这种情况还可以继续使用
            //内容的return,会导致三个现象,
            //  1.capacity永远不会>MAXIMUM_CAPACITY.成不了负数,不会溢出
            //  2.threshold用于不会>Integer.MAX_VALUE.成不了负数,不会溢出
            //  3.capacity,threshold达到极限后,依然可以添加元素,不会出错,但内存容量有限
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            //如果现在的容量再扩容小于最大容量,并且现在的容量大于默认容量16
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                    oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; // double threshold
        }
        //如果老的临界值大于0,就把临界值赋值给容量,
        // 有参构造,第一次添加元素需要扩容时就会走这里
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;
        //如果如果oldCap和oldThr都不大于0,就初始化
        //无参构造才会走这里
        else {               // zero initial threshold signifies using defaults
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
        //针对oldThr > 0的情况
        //有参构造,才会出现这个情况
        if (newThr == 0) {
            float ft = (float)newCap * loadFactor;
            newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                    (int)ft : Integer.MAX_VALUE);
        }
        threshold = newThr;
        //是时候table了
        @SuppressWarnings({"rawtypes","unchecked"})
        HashMapInit.Node<K,V>[] newTab = (HashMapInit.Node<K,V>[])new HashMapInit.Node[newCap];
        table = newTab;
        if (oldTab != null) {
            //转移数据
            for (int j = 0; j < oldCap; ++j) {
                HashMapInit.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 HashMapInit.TreeNode)
                        ((HashMapInit.TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                    else { // preserve order
                        HashMapInit.Node<K,V> loHead = null, loTail = null;
                        HashMapInit.Node<K,V> hiHead = null, hiTail = null;
                        HashMapInit.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;
    }

    /**
     * 返回comparable<C>类
     */
    static Class<?> comparableClassFor(Object x) {
        if (x instanceof Comparable) {
            Class<?> c; Type[] ts, as; Type t; ParameterizedType p;
            if ((c = x.getClass()) == String.class) // bypass checks
                return c;
            if ((ts = c.getGenericInterfaces()) != null) {
                for (int i = 0; i < ts.length; ++i) {
                    if (((t = ts[i]) instanceof ParameterizedType) &&
                            ((p = (ParameterizedType)t).getRawType() ==
                                    Comparable.class) &&
                            (as = p.getActualTypeArguments()) != null &&
                            as.length == 1 && as[0] == c) // type arg is c
                        return c;
                }
            }
        }
        return null;
    }

    /**
     * 比较
     */
    @SuppressWarnings({"rawtypes","unchecked"}) // for cast to Comparable
    static int compareComparables(Class<?> kc, Object k, Object x) {
        return (x == null || x.getClass() != kc ? 0 :
                ((Comparable)k).compareTo(x));
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值