学习HashMap源码

HashMap源码理解

jdk1.8 主要的几个方法理解

属性
   /**
     * 默认初始容量。
     */
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

    /**
     * 最大支持容量
     * MUST be a power of two <= 1<<30.
     */
    static final int MAXIMUM_CAPACITY = 1 << 30;

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

    /**
     * 链表长度大于8转为红黑树.
     */
    static final int TREEIFY_THRESHOLD = 8;

    /**
     * 链表长度等于6的时候从红黑树转为链表
     */
    static final int UNTREEIFY_THRESHOLD = 6;

    /**
     * 红黑树的多大的时候开始扩容
     */
    static final int MIN_TREEIFY_CAPACITY = 64;
   

    /**
     * 存储元素的数组
     */
    transient Node<K,V>[] table;

    /**
     * 存储具体元素的集
     */
    transient Set<Entry<K,V>> entrySet;

    /**
     * key-value的数量
     */
    transient int size;

    /**
     * HashMap扩容和结构改变的次数
     */
    transient int modCount;

    /**
     * 扩容临界值 (capacity * load factor).
     *
     * @serial
     */
    int threshold;

    /**
     * 填充因子
     */
    final float loadFactor;
Node节点定义
  /**
     * 节点的Node,继承Entry
     */
    static class Node<K,V> implements Entry<K,V> {
    
    
        final int hash; //hash用来定位数组索引位置
        final K key;  
        V value;
        Node<K,V> next;  //下一个节点对应的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; }

        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) {
    
    
                Entry<?,?> e = (Entry<?,?>)o;
                if (Objects.equals(key, e.getKey()) &&
                    Objects.equals(value, e.getValue()))
                    return true;
            }
            return false;
        }
    }
构造器
    /**
     * 构造器,设置默认大小和负载因子
     * @param  initialCapacity the initial capacity
     * @param  loadFactor      the load factor
     * @throws IllegalArgumentException if the initial capacity is negative
     *         or the load factor is nonpositive
     */
    public HashMap(int initialCapacity, float loadFactor) {
    
    
        /***
         * 如果initialCapacity赋值大小小于0抛出异常
         */
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " +
                                               initialCapacity);
        /***
         * 如果initialCapacity赋值大小大于最大支持容量,就设置容量为最大支持容量。
         */
        if (initialCapacity > MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;

        /***
         * 如果负载因子小于0或者不是float,抛出异常
         */
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal load factor: " +
                                               loadFactor);
        /***
         * 设置负载因子
         */
        this.loadFactor = loadFactor;
        /***
         * 扩容临界值的大小
         */
        this.threshold = tableSizeFor(initialCapacity);
    }

    /**
     * 构造器,设置默认大小和负载为默认的DEFAULT_LOAD_FACTOR
     * @param  initialCapacity the initial capacity.
     * @throws IllegalArgumentException if the initial capacity is negative.
     */
    public HashMap(int initialCapacity) {
    
    
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }

    /**
     * 无参构造器,只设置赋值因子DEFAULT_LOAD_FACTOR
     */
    public HashMap() {
    
    
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }

    /**
     * 对于给定的目标容量,返回两倍大小的幂.
     */
    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;
    }
添加方法及添加涉及到的方法

两个算法说明

hash = (h = key.hashCode()) ^ (h >>> 16)

”东东“ .hashCode()10011100001110000000

”东东“ .hashCode() >>> 1611111111111111111001

”东东“ .hashCode()^”东东“ .hashCode() >>> 1610011100001110001001

(lenth - 1) & hash :存储的位置

如果默认lenth为最初始化的1616二进制:           00000000000000010000

16 - 1 = 15 的二进制: 						   00000000000000001111

hash		                                   10011100001110001001

(lenth - 1) & hash:                           00000000000000001001

这样就能完美的把值放到16个桶中了。。。

    
    /***
     * 根据key获得hash值
     * @param key
     * @return
     */
    static final int hash(Object key) {
    
    
        int h;
        //返回的值如果是null,就返回0,否者
        //h = key.hashCode()获取key的hashCode;
        //h >>> 16 无符号右移16位
        //h = key.hashCode()) ^ (h >>> 16) hash值和无符号右移16位的值进行异或运算
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }



 /**
     * HashMap底层是用数组+链表(红黑树)组成的
     * @param hash hash for key
     * @param key the key
     * @param value the value to put
     * @param onlyIfAbsent if true, don't change existing value
     * @param evict if false, the table is in creation mode.
     * @return previous value, or null if none
     */
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
    
    

        Node<K,V>[] tab;  //存储数据的数组
        Node<K,V> p;

        int n, i; //记录数组的长度

        //如果数组还是空
        if ((tab = table) == null || (n = tab.length) == 0)
            //进行扩容(HashMap不是开始赋值的初始值的)
            n = (tab = resize()).length;

        //(n - 1) & hash 位置上没有值
        // n - 1 长度都为2的n次方获的值所有的位置都是1
        // 与hash进行进行&运算,巧妙的获取到了具体位置
        if ((p = tab[i = (n - 1) & hash]) == null)
            //put到 (n - 1) & hash上
            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;
                //如果当前位置的值是TreeNode,就进行挂到红黑树
            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;
            }
        }
        //扩容和结构改变的次数+1
        ++modCount;
        //如果长度大于扩容临界值进行扩容
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }


 /**
     * 扩容操作
     * @return the table
     */
    final Node<K,V>[] resize() {
    
    
        //数组先复制给oldTab
        Node<K,V>[] oldTab = table;
        //获得数组的长度
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        //获取当前数组的扩容临界值
        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 = oldThr;
        else {
    
                   // 第一次put的时候,没有值,就设置默认初始大小16,且设置其的扩容临界值
            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 = newThr;

        /***
         *  @SuppressWarnings注解去掉代码警告
         */
        @SuppressWarnings({
    
    "rawtypes","unchecked"})
        /***
         * 正式开始put操作及扩容操作
         */
         Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
        table = newTab;
        /***
         * 如果以前数组有值
         */
        if (oldTab != null) {
    
    
            //遍历以前的数组
            for (int j = 0; j < oldCap; ++j) {
    
    
                Node<K,V> e;
                if ((e = oldTab[j]) != null) {
    
    
                    oldTab[j] = null;
                    //如果当前数组的Node下一个值为空,把值重写hash赋值到新的数组上
                    if (e.next == null)
                        newTab[e.hash & (newCap - 1)] = e;
                    //如果当前数组是红黑树,把当树上的值重新赋值到新的Table上
                    else if (e instanceof TreeNode)
                        ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                    else {
    
     // 数组上是链表。对链表的只进行挂到新的table上
                        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;
    }

jdk1.7 以后更新~~~~~~~~~~~~~

猜你喜欢

转载自blog.csdn.net/weixin_35133235/article/details/106039873