Map之HashMap源码实现

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_39723544/article/details/83033694

一、引言

1.导语

在此之前学习HashMap之前,我们首先对先前学习的List进行总结一些:

类型 说明
ArrayList 底层是数组,顺序插入。查询快、增删慢
LinkedList 底层是链表,顺序插入。查询慢、增删块

但是这样的集合我们还是不满意啊,有没有查询块,增删也快的集合,那 就是我们今天要学习的HashMap。

2.要点

要点 说明
是否可以为空 key和value都可以为空,但是key只能一个为空,value则不限
是否有序 无序
是否可以重复 key重复会覆盖,value则可以重复
是否线程安全 非线程安全

二、分析

1.继承关系图

在这里插入图片描述

2.字段

   /**
     * The default initial capacity - MUST be a power of two.
     * 默认的容量
     */
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

    /**
     * 最大容量上限
     */
    static final int MAXIMUM_CAPACITY = 1 << 30;

   /**
     * 负载因子,调控控件与冲突率的因数
     */
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

   /**
     * 链表转换为树的阈值,超过这个长度的链表会被转换为红黑树
     */
    static final int TREEIFY_THRESHOLD = 8;

    /**
     * The bin count threshold for untreeifying a (split) bin during a
     * resize operation. Should be less than TREEIFY_THRESHOLD, and at
     * most 6 to mesh with shrinkage detection under removal.
     * 当进行resize操作时,小于这个长度的树会被转换为链表
     */
    static final int UNTREEIFY_THRESHOLD = 6;

    /**
     * The smallest table capacity for which bins may be treeified.
     * (Otherwise the table is resized if too many nodes in a bin.)
     * Should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts
     * between resizing and treeification thresholds.
     * 链表被转换成树形的最小容量,如果没有达到这个容量只会执行resize进行扩容
     */
    static final int MIN_TREEIFY_CAPACITY = 64;

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

    /**
     * Holds cached entrySet(). Note that AbstractMap fields are used
     * for keySet() and values().
     * set数组,用于迭代元素
     */
    transient Set<Map.Entry<K,V>> entrySet;

    /**
     * 存放元素的个数,但不等于数组的长度
     */
    transient int size;

    /**
     * 修改的次数
     */
    transient int modCount;

    /**
     * The next size value at which to resize (capacity * load factor).
     *
     * 临界值  如果实际大小超过临界值,就会进行扩容。threshold=加载因子 * 容量
     */
    int threshold;

    /**
     * 加载因子
     *
     * @serial
     */
    final float loadFactor;

2.构造方法

    /**
     * Constructs an empty <tt>HashMap</tt> with the specified initial
     * capacity and load factor.
     *
     * @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) {
        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;
        this.threshold = tableSizeFor(initialCapacity);
    }

    /**
     * Constructs an empty <tt>HashMap</tt> with the specified initial
     * capacity and the default load factor (0.75).
     *
     * @param  initialCapacity the initial capacity.
     * @throws IllegalArgumentException if the initial capacity is negative.
     * 参数为初始化大小
     */
    public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }

    /**
     * Constructs an empty <tt>HashMap</tt> with the default initial capacity
     * (16) and the default load factor (0.75).
     * 默认无参构造方法
     */
    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }

    /**
     * Constructs a new <tt>HashMap</tt> with the same mappings as the
     * specified <tt>Map</tt>.  The <tt>HashMap</tt> is created with
     * default load factor (0.75) and an initial capacity sufficient to
     * hold the mappings in the specified <tt>Map</tt>.
     *
     * @param   m the map whose mappings are to be placed in this map
     * @throws  NullPointerException if the specified map is null
     * 参数为集合
     */
    public HashMap(Map<? extends K, ? extends V> m) {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        putMapEntries(m, false);
    }

3.HashMap的实现原理

3.1图示

在这里插入图片描述

3.2分析

  • 链表的实现如下
    /**
     * Basic hash bin node, used for most entries.  (See below for
     * TreeNode subclass, and in LinkedHashMap for its Entry subclass.)
     * 相比LinkedList的双向列表,Node是一个单向列表,通过next来实现
     */
    static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        V value;
        Node<K,V> next;

        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) {
                Map.Entry<?,?> e = (Map.Entry<?,?>)o;
                if (Objects.equals(key, e.getKey()) &&
                    Objects.equals(value, e.getValue()))
                    return true;
            }
            return false;
        }
    }
  • 红黑树的实现(待补充(后面会有一篇专门的文章研究)):
static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
        TreeNode<K,V> parent;  // red-black tree links
        TreeNode<K,V> left;
        TreeNode<K,V> right;
        TreeNode<K,V> prev;    // needed to unlink next upon deletion
        boolean red;
        TreeNode(int hash, K key, V val, Node<K,V> next) {
            super(hash, key, val, next);
        }
}

4.方法

4.1 存储:put(K key, V value)方法

	// 需要放入的键与值
    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }
        /**
     * Implements Map.put and related methods
     *
     * @param hash hash for key  键值的hash值
     * @param key the key         键值
     * @param value the value to put   值 
     * @param onlyIfAbsent if true, don't change existing value   如果为true,如果放入已存在key,value则不会覆盖
     * @param evict if false, the table is in creation mode.  如果是false,table数组是创建模式,这里用不到,hash值才能用到。
     * @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;
        // 如果table数组为空或长度为0,则对其进行初始化,分配内存空间
        if ((tab = table) == null || (n = tab.length) == 0) 
            n = (tab = resize()).length;
        if ((p = tab[i = (n - 1) & hash]) == null)
        	// 当put的key在数组中不存在时,直接new一个Node元素放入
            tab[i] = newNode(hash, key, value, null);
        else {
           // 此种情况是key元素在集合中已存在的情况
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k)))) // 如果tab[(n - 1) & hash]位置的第一个元素的key和要保存的key相等,则将p的值赋值给e,在后面进行替换
                e = p;
            else if (p instanceof TreeNode)  // 如果是红黑树节点,则调用其put方法
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {  // table[[(n - 1) & hash]第一个节点不符合要求,则循环其中的每一个元素
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) { // 此处主要是为了防止hash碰撞,则put的key在此链表不存在
                        p.next = newNode(hash, key, value, null);
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st 如果链表的长度超过8,则进行红黑树进行转换。1,8后追加:链表查询的复杂度是O(n),而红黑树是O(log(n)),但是如果hash结果不均匀会极大的影响性能
                            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;
        if (++size > threshold)
            resize(); // 如果size大于扩容阀值,则进行扩容操作
        afterNodeInsertion(evict);
        return null;
    }

4.2扩容:resize()

 final Node<K,V>[] resize() {
        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) { // 如果目前table的容量大于最大容量的上限,则不会进行扩容
                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
           // 这个分支是针对默认构造函数的分支,对newCap和newThr进行赋值
            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({"rawtypes","unchecked"})
            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) {
                    //将原来的置为 null,方便垃圾回收器进行回收
                    oldTab[j] = null; 
                    // 如果e.next为null,表示此链表是单节点,直接根据e.hash & (newCap - 1)得到新的位置进行赋值即可
                    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
                    	// 此分支是:链表的复制
                    	// 而且其元素在数组中位置确定的方式:
                    	// 不是根据hash算法生成新的位置,而是采用了原始位置+原始长度得到新的位置
                        Node<K,V> loHead = null, loTail = null;
                        Node<K,V> hiHead = null, hiTail = null;
                        Node<K,V> next;
                        do {
                            next = e.next;
                            // 判断:元素的在数组中的位置是否需要移动
                            // (e.hash & oldCap)结果为0就代表没有变化,否则就是有变化
                            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) {
                        	// 将链表的尾部的next置为空
                            loTail.next = null;
                            newTab[j] = loHead; 
                        }
                        if (hiTail != null) {
                        	// 将链表的尾部的next置为空
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }

4.3获取:get(Object key)

   public V get(Object key) {
        Node<K,V> e;
        // 可以看出主干方法在getNode(key)里面
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }

    final Node<K,V> getNode(int hash, Object key) {
        Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
        // 通过key的hash定位到桶的位置,并且第一个元素不是null
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {
            // 总是检查第一个节点
            // 如果第一个节点的hash值且key值也相等,直接返回first元素 
            if (first.hash == hash && // always check first node
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
            if ((e = first.next) != null) {
            	// 判断next节点是不是红黑树节点,如果是直接调用其getTreeNode方法得到其treeNode节点
                if (first instanceof TreeNode)
                    return ((TreeNode<K,V>)first).getTreeNode(hash, key);
                // 进行循环,去除符合条件的Node节点。循环的结束的条件是:直到链表的尾部
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;
    }

4.4 Map集合复制:putMapEntries(Map<? extends K, ? extends V> m, boolean evict)

    public HashMap(Map<? extends K, ? extends V> m) {
    	// 负载因子初始化
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        // 真正进行map复制的方法
        putMapEntries(m, false);
    }

    final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
        int s = m.size();
        // 传入的map不为空的情况下进行复制操作
        if (s > 0) {
        	// table未初始化,s为传入集合的元素个数
            if (table == null) { // pre-size
                float ft = ((float)s / loadFactor) + 1.0F;
                int t = ((ft < (float)MAXIMUM_CAPACITY) ?
                         (int)ft : MAXIMUM_CAPACITY);
                // 如果t大于阈值,则初始化阀值
                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);
            }
        }
    }

4.5 其他1:hash(Object key)

    static final int hash(Object key) {
        int h;
        // 通过hashCode()的高16位异或低16位实现:
        // 速度、功效、质量来考虑的,这么做可以在数组table的length比较小的时候,也能保证     	考虑到高低Bit都参与到Hash的计算中,同时不会有太大的开销
        // 参考:https://blog.csdn.net/login_sonata/article/details/76598675 部分内容
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

4.6 其他2:tableSizeFor(int cap)

	// 作用:返回给定参数的最小二次幂的值.
	// 我们知道,HashMap的capacity的值必须是2的次幂;
    static final int tableSizeFor(int cap) {
    	// 先看一个规律:
    	// 7 = 0111,其最小2^次幂为1000 = 0111+1
    	// 11=1011,其最小2^次幂为10000 = 01111+1
    	// 29 = 011101,其最效2^次幂为100000 = 011111+1
    	// 由此我们得到:对于给定的整数cap,其二进制第一次出现1的位数为n,那么气最小的二次幂的值为:2^(n + 1) 或 2^n
		
		// 看这个方法的代码如下:
		// n |= n >>> 1 是为了确保第一个1及其其后1位都是1
		//  n |= n >>> 2 是为了确保第一个1及其其后3位都是1
		//  n |= n >>> 4 是为了确保第一个1及其其后7位都是1
		//  n |= n >>> 8 是为了确保第一个1及其其后15位都是1
		//  n |= n >>>16 是为了确保第一个1及其其后所有位都是1
		// 所以大于cap的最小的2次幂就是(n + 1).
        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;
    }

三、结语

3.1回顾

回顾下上面的存储、扩容、获取等关键代码实现,再结合学习的四个要点,去对比理解其中的设计原理。

3.2思考

  • HashMap的是怎么保证添加的元素的索引的(也就是说哈希桶是如何分布的)?
  • HshMap的扩容的流程是怎么样的?
  • 1.8比1.7版本在HashMap的那些方面做了改动和优化?
  • HashMap的hash算法是怎么实现的?为什么要这么实现?

3.3 关于红黑树理解在这里:待完善

猜你喜欢

转载自blog.csdn.net/weixin_39723544/article/details/83033694
今日推荐