JDK1.8 HashMap源码解析

    // 序列号
    private static final long serialVersionUID = 362498820763181265L;

    // 默认的初始容量大小是16
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

    //hashmap的最大容量为2的30次方
    static final int MAXIMUM_CAPACITY = 1 << 30;

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

    // 当桶(bucket)上的结点数大于这个值时会转成红黑树
    static final int TREEIFY_THRESHOLD = 8;

    // 当桶(bucket)上的结点数小于这个值时树转链表
    static final int UNTREEIFY_THRESHOLD = 6;

    // 桶中结构转化为红黑树对应的table的最小大小
    static final int MIN_TREEIFY_CAPACITY = 64;


    static class Node<K,V> implements Map.Entry<K,V> {
        //final类型node节点的hash值
        final int hash;
        //final类型的key值
        final K key;
        //value值
        V value;
        //node节点的next
        Node<K,V> next;

        //class node的构造函数
        Node(int hash, K key, V value, 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; }
        //hashcode方法
        public final int hashCode() {
            return Objects.hashCode(key) ^ Objects.hashCode(value);
        }

        public final V setValue(V newValue) {
            V oldValue = value;
            value = newValue;
            return oldValue;
        }
        //equals方法
        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;
        }
    }


    // 存储元素的数组,总是2的幂次倍
    transient Node<K,V>[] table;

    // 存放具体元素的集
    transient Set<Map.Entry<K,V>> entrySet;

     // 存放元素的个数,注意这个不等于数组的长度。
    transient int size;

    // 每次扩容和更改map结构的计数器
    transient int modCount;

    // 临界值 当实际大小(容量*填充因子)超过临界值时,hashmap会进行扩容
    int threshold;

    // 填充因子
    final float loadFactor;

    //关于下列函数的详细解析参看博客        
    //https://blog.csdn.net/fan2012huan/article/details/51097331
   static final int tableSizeFor(int cap) {
        //防止cap数值已经是2的幂次方。如果cap已经是2的幂次方, 又没有执行减1操作,则执行完后面的几条无符号右移操作之后,返回的capacity将是这个cap的2倍。
        int n = cap - 1;
        n |= n >>> 1;//二进制数值右移一位并与原值进行或操作
        n |= n >>> 2;//二进制数值右移二位并与原值进行或操作
        n |= n >>> 4;//二进制数值右移四位并与原值进行或操作
        n |= n >>> 8;//二进制数值右移八位并与原值进行或操作
        n |= n >>> 16;//二进制数值右移16位并与原值进行或操作
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
    }
    
    //key的hash值高16位不变,低16位与高16位异或作为key的最终hash值。
    //(h >>> 16,表示无符号右移16位,高位补0,任何数跟0异或都是其本身,
    //因此key的hash值高16位不变。
    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }
    
    hashmap的构造函数
    
    //空参构造函数,DEFAULT_LOAD_FACTOR默认为0.75f,其他所有的字段初始值均为默认。
    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }
    //此构造函数会默认调用HashMap(int, float)型构造函数
    //DEFAULT_LOAD_FACTOR 默认为:0.75f
    public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }

    public HashMap(int initialCapacity, float loadFactor) {
        // 初始容量不能小于0,否则会抛出异常
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " +
                                               initialCapacity);
        //判断初始容量与最大容量,如果超过最大容量,则将最大容量赋值为初始容量
        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初始化, 当实际大小(容量*填充因子)超过临界值时,hashmap会进行扩容
        //tableSizeFor函数(initialCapacity)返回大于等于initialCapacity的最小的二次幂数值
        this.threshold = tableSizeFor(initialCapacity);
    }

    public HashMap(Map<? extends K, ? extends V> m) {
        //使用默认的DEFAULT_LOAD_FACTOR为0.75f
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        //调用putMapEntries()函数,将m中的值,放入hashMap中
        putMapEntries(m, false);
    }
    
    
    final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
        //获取m的size
        int s = m.size();
        if (s > 0) {
            //判断table是否已经初始化
            if (table == null) { // pre-size
                 // 未初始化,s为m的实际元素个数
                float ft = ((float)s / loadFactor) + 1.0F;
                //判断ft是否大于MAXIMUM_CAPACITY,将最小值赋值于t
                int t = ((ft < (float)MAXIMUM_CAPACITY) ?
                         (int)ft : MAXIMUM_CAPACITY);
                // 计算得到的t大于阈值,则初始化阈值
                if (t > threshold)
                    //初始化为t的最近的2的次方幂
                    threshold = tableSizeFor(t);
            }
            // 如果table已初始化,并且m元素个数大于阈值,进行扩容处理
            else if (s > threshold)
                resize();
            //循环迭代,将m中的值放入hashmap中
            for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
                K key = e.getKey();
                V value = e.getValue();
                //调用putVal函数将key与Value插入hashmap中
                putVal(hash(key), key, value, false, evict);
            }
        }
    }
    

    //HashMap并没有直接提供putVal接口给用户调用,而是提供的put函数,而put函数就是通过putVal来插入元素的。
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        /**先定义一个临时Node节点数组tab,p是单个节点的变量,n表示节点数组表的长度,i表示tab数组索引位置*/
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        // 如果table未初始化或者长度为0,进行扩容
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        // (n - 1) & hash 确定元素存放在哪个桶bucket中,桶bucket为空,新生成结点放入桶bucket中(此时,这个结点是放在数组中)
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        // 桶bucket中已经存在元素
        else {
            Node<K,V> e; K k;
            // 比较桶bucket中第一个元素(数组中的结点)的hash值是否相等,key是否相等
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;// 将第一个元素赋值给e,用e来记录
            else if (p instanceof TreeNode)// hash值不相等,即key不相等;为红黑树结点
                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;
                    }
                    // 判断链表中结点的key值与插入的元素的key值是否相等
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        // 相等,跳出循环
                        break;
                     // p用于遍历桶bucket中的链表,与前面的e = p.next组合,可以遍历链表
                    p = e;
                }
            }
            // 表示在桶bucket中找到key值、hash值与插入元素相等的结点
            if (e != null) { // existing mapping for key
                // 保存e的value
                V oldValue = e.value;
                // onlyIfAbsent为false或者旧值为null
                if (!onlyIfAbsent || oldValue == null)
                    //用新值替换旧值
                    e.value = value;
                // 访问后回调函数afterNodeAccess()
                afterNodeAccess(e);
                //返回旧值
                return oldValue;
            }
        }
        //modCount自增1
        ++modCount;
        //如果实际大小大于阈值则扩容即resize操作
        if (++size > threshold)
            resize();
        // 插入后回调函数
        afterNodeInsertion(evict);
        return null;
    }
   // hashMap并没有直接提供getNode接口给用户调用,而是提供的get函数,而get函数就是通过getNode来取得元素的   

    final Node<K,V> getNode(int hash, Object key) {
        Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
        // 如果table已经初始化,长度大于0,根据hash寻找table中的项也不为空
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {
             // 判断桶bucket中第一个节点(数组元素)的hash是否相等,key值是否相等
            if (first.hash == hash && // always check first node
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
            // 桶bucket中next结点不为null,即桶bucket中不止一个节点
            if ((e = first.next) != null) {
                // 如果节点为为红黑树结点
                if (first instanceof TreeNode)
                    // 在红黑树中查找该节点
                    return ((TreeNode<K,V>)first).getTreeNode(hash, key);
                // 否则,在链表中查找是否存在该节点
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        //节点不存在,则返回null值
        return null;
    }
resize()函数
//参看于https://www.cnblogs.com/leesf456/p/5242233.html   
//参看于https://blog.csdn.net/Z0157/article/details/82357054
final Node<K,V>[] resize() {
    // 当前table保存
    Node<K,V>[] oldTab = table;
    // 获取table大小
    int oldCap = (oldTab == null) ? 0 : oldTab.length;
    // 保存当前阈值 
    int oldThr = threshold;
    /** newCap:定义一个新的临时容量变量,newThr:定义个新的临时的threshold*/
    int newCap, newThr = 0;
    // 当旧table大小大于0时
    if (oldCap > 0) {
        // 之前table大于最大容量
        if (oldCap >= MAXIMUM_CAPACITY) {
            // 阈值为最大整形
            threshold = Integer.MAX_VALUE;
            return oldTab;
        }
        // 容量翻倍,使用左移,效率更高
        else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
            oldCap >= DEFAULT_INITIAL_CAPACITY)
            // 阈值翻倍
            newThr = oldThr << 1; /** newThr = oldCap*2 = threshold*2*/
    }
    // 之前阈值大于0
    else if (oldThr > 0)
        newCap = oldThr;
    // oldCap = 0并且oldThr = 0,使用缺省值(如使用HashMap()构造函数,之后再插入一个元素会调用resize函数,会进入这一步)
    else {
         /** 这种情况就是构造HashMap的时候,threshold初始化是0,第一次put数据resize,则我们就给newCap赋值默认的初始化的容量16,newThr = 16*0.75
             * */           
        newCap = DEFAULT_INITIAL_CAPACITY;
        newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
    }
    // 新阈值为0
    if (newThr == 0) {
        float ft = (float)newCap * loadFactor;
        newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                  (int)ft : Integer.MAX_VALUE);
    }
    threshold = newThr;
    @SuppressWarnings({"rawtypes","unchecked"})
    // 初始化table
    Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
    table = newTab;
        /** 如果扩充前oldTab的值不是null值,那我们将进行把之前的旧值赋值到对应的newTab中*/
        if (oldTab != null) {
            /**遍历循环oldCap*/
            for (int j = 0; j < oldCap; ++j) {
                Node<K,V> e;
                if ((e = oldTab[j]) != null) {
                    oldTab[j] = null; /** 如果j位置有节点元素,则取出该元素e,并且把数组中的该位置的node节点赋值null*/
                    if (e.next == null)/** 如果下个节点没有数据了(也就是链表的尾部),则把e,放在newTab位置为e.hash & (newCap - 1) 的地方*/
                        newTab[e.hash & (newCap - 1)] = e;
                    else if (e instanceof TreeNode)/** 如果是红黑树(点进split方法继续跟踪),重新映射,对红黑树进行split*/
                        ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                    else { // preserve order
                        /** 如果该节点是链表的存储
                         *  如果你对链表的结构,和java操作链表不会,那很难看懂
                         * */
                        Node<K,V> loHead = null, loTail = null;
                        Node<K,V> hiHead = null, hiTail = null;
                        Node<K,V> next;
                        /** 维持原来的链表的节点顺序进行rehash*/
                        do {
                            next = e.next; /** 当前节点指向的下一个节点地址*/
                            /** 原索引*/
                            if ((e.hash & oldCap) == 0) {/** e.hash & oldCap 这个计算的值,是节点数组的位置索引*/
                                if (loTail == null)
                                    loHead = e;
                                else
                                    loTail.next = e;
                                loTail = e;
                            }
                            else {/** 原所以加上oldCap*/
                                if (hiTail == null)
                                    hiHead = e;
                                else
                                    hiTail.next = e;
                                hiTail = e;
                            }
                        } while ((e = next) != null);
                        /** 原索引放在bucket里*/
                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead;
                        }
                        /** 原索引+ oldCap放在bucket里*/
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                        /**
                         * 总结:
                         * 经过rehash之后,元素的位置要么在原来的位置,要么在原来的位置
                         * 再移动2次幂。
                         * */
                    }
                }
            }
        }
 
        return newTab;
    }

猜你喜欢

转载自blog.csdn.net/zxk082829/article/details/89743655