HashMap底层原理及其扩容机制(源码解析)

 hashset : 调用add方法时也是调用map的put方法

        key为传的值

        value为一个object对象


    /**
     * Adds the specified element to this set if it is not already present.
     * More formally, adds the specified element <tt>e</tt> to this set if
     * this set contains no element <tt>e2</tt> such that
     * <tt>(e==null&nbsp;?&nbsp;e2==null&nbsp;:&nbsp;e.equals(e2))</tt>.
     * If this set already contains the element, the call leaves the set
     * unchanged and returns <tt>false</tt>.
     *
     * @param e element to be added to this set
     * @return <tt>true</tt> if this set did not already contain the specified
     * element
     */
    public boolean add(E e) {
        return map.put(e, PRESENT)==null;
    }
//无参实例化一个map对象
Map<String,String> map = new HashMap();

    //构造一个带有默认初始容量(16)和默认负载因子(0.75)的空哈希映射。
    /**
     * Constructs an empty <tt>HashMap</tt> with the default initial capacity
     * (16) and the default load factor (0.75).
     */
    public HashMap() {
        //DEFAULT_LOAD_FACTOR--默认加载因子0.75
        //给当前map对象的加载因子赋默认值
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }
map.put("aa","bb")


     //当执行put方法时执行putVal方法,并且返回该key对应的上一个所对应value的值,如果没有对应的 
     //映射则返回为null
    /**
     * Associates the specified value with the specified key in this map.
     * If the map previously contained a mapping for the key, the old
     * value is replaced.
     *
     * @param key key with which the specified value is to be associated
     * @param value value to be associated with the specified key
     * @return the previous value associated with <tt>key</tt>, or
     *         <tt>null</tt> if there was no mapping for <tt>key</tt>.
     *         (A <tt>null</tt> return can also indicate that the map
     *         previously associated <tt>null</tt> with <tt>key</tt>.)
     */
    public V put(K key, V value) {
        //hash() 通过执行hashcode方法计算hash值
        //(h = key.hashCode()) ^ (h >>> 16)
        return putVal(hash(key), key, value, false, true);
    }

HashMap.Node是Map.Entry的具体实现类,记录节点hash,key,value,next,用于存储单向链表数据结构的数据

JDK1.8 改使用Node<K,V>    JDK1.7之前使用Entry<K,V>


    /**
     * Basic hash bin node, used for most entries.  (See below for
     * TreeNode subclass, and in LinkedHashMap for its Entry subclass.)
     */
    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;
        }
    }

    /**
     * Implements Map.put and related methods
     * 实现map.put及相关方法
     *
     * @param hash hash for key -- key的hash值
     * @param key the key --key
     * @param value the value to put --需要put的value值
     * @param onlyIfAbsent if true, don't change existing value -- onlyIfAbsent 如果为 
     * true,则不更改现有值
     * @param evict if false, the table is in creation mode. --如果为false,则表处于创建模 
     * 式。
     * @return previous value, or null if none --上一个值,如果没有,则为null
     */
    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赋值给新变量tab 判断是否为空 如果为空则进行初始化
        //该对象第一次put数据时进行初始化
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;

        //后面put数据时 现将该节点位置元素取出赋给p  并判断该节点是否有元素   
        if ((p = tab[i = (n - 1) & hash]) == null)
            //如果没有的话  直接把该元素存放至此节点
            tab[i] = newNode(hash, key, value, null);
       //有元素
        else { 
            
            Node<K,V> e; K k;

            //hash值相等时与该节点的第一个元素进行比较,如果key相等将该节点元素取出
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;

            //如果此节点是红黑树存的 调用红黑树的putTreeVal方法
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);


            //如果是链表  遍历到最后节点 使用尾插法加入新节点
            else {
                for (int binCount = 0; ; ++binCount) {

                    
                    //将该节点的下一个节点元素赋给e
                    //最后节点
                    if ((e = p.next) == null) { 
                        //插入该元素
                        p.next = newNode(hash, key, value, null);
                        //该节点元素超过8
                        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指向下一个节点的元素用于循环
                    p = e;
                }
            }
            
            //e不为空 表明map中已经存在了该key 将该key对应的value换成新的value
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }

        //用于线程安全和迭代器进行比较用于hasnext
        ++modCount;

        //超过规定范围 则进行扩容
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

    /**
     * Initializes or doubles table size.  If null, allocates in
     * accord with initial capacity target held in field threshold.
     * Otherwise, because we are using power-of-two expansion, the
     * elements from each bin must either stay at same index, or move
     * with a power of two offset in the new table.
     *
     * @return the table
     */
    final Node<K,V>[] resize() {
        //初始化的table赋值
        Node<K,V>[] oldTab = table;

        //判断table是否初始化了,如果没有初始化则oldCap置为1,否则是初始化的长度
        //put前的容量
        int oldCap = (oldTab == null) ? 0 : oldTab.length;

        //threshold-阈值,超过阈值会进行扩容 初始阈值为0
        //put前的阈值
        int oldThr = threshold;

        int newCap, newThr = 0; 定义新容量新阈值


        //put前已经有初始容量
        if (oldCap > 0) {
            //如果put前容量 >= 最大容量2的30次幂
            if (oldCap >= MAXIMUM_CAPACITY) {

                //阈值扩大到最大的int值 2^31-1
                threshold = Integer.MAX_VALUE;

                return oldTab;//返回put前的node[]
            }
            //如果是之前的容量扩大到2倍之后还小于map最大容量 并且  之前的容量超过初始容量16
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                //新的阈值 为 老的阈值的两倍
                newThr = oldThr << 1; // double threshold
        }
        
        //put前的阈值大于0
        else if (oldThr > 0)
            newCap = oldThr;  // 初始容量被置于阈值
        else {               
            //零初始阈值表示使用默认值
            //16 初始容量
            newCap = DEFAULT_INITIAL_CAPACITY;
            //(0.75*16)初始阈值
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }

        //新阈值为0
        if (newThr == 0) {
            float ft = (float)newCap * loadFactor;
            //新阈值=如果新容量<最大容量 并且阈值也小于最大容量则为当前容量*加载因子否则为最 
            //大的int值
            newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                      (int)ft : Integer.MAX_VALUE);
        }
        //修改当前map阈值为新阈值
        threshold = newThr;
        @SuppressWarnings({"rawtypes","unchecked"}) //禁止显示警告
            //new一个新的长度为新容量的node[]
            Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];

        //修改当前map中node[]
        table = newTab;

        //老的table存在
        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;
                        }
                    }
                }
            }
        }
        //返回这个重新构建的node[]
        return newTab;
    }
/**
     * Replaces all linked nodes in bin at index for given hash unless
     * table is too small, in which case resizes instead.
     */
    final void treeifyBin(Node<K,V>[] tab, int hash) {
        int n, index; Node<K,V> e;
        //进行判断,该node数组是否存在并且该node长度是否小于64
        //如果小于64则进行扩容
        if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
            resize();
        else if ((e = tab[index = (n - 1) & hash]) != null) {
            TreeNode<K,V> hd = null, tl = null;
            do {
                TreeNode<K,V> p = replacementTreeNode(e, null);
                if (tl == null)
                    hd = p;
                else {
                    p.prev = tl;
                    tl.next = p;
                }
                tl = p;
            } while ((e = e.next) != null);
            if ((tab[index] = hd) != null)
                hd.treeify(tab);
        }
    }

总结:

      首先实例化map时会将该map的初始对象的加载因子设置为默认值0.75;

      当map执行put方法时

      map首先会判断当前map的Node数组是否已经实例化过并且当前Node数组长度是否大于0,如果当前map是第一次执行put方法,则会调用resize()方法进行初始化,建造一个初始容量为16的Node数组(JDK1.7为Entry,Node实现了Entry接口),并对map对象的阈值也进行初始化,阈值为16 * 0.75 = 12,Node数组初始化完成之后,

会根据当前map的key值计算出来的hash值与当前Node数组最大索引值做与运算计算出当前key-value所应该存放在该Node数组中的位置,

如果该位置没有元素的话,会用key value实例化一个Node对象存放在该位置,

如果该位置已经存在元素,会和该位置第一个节点元素key进行比较;

1)如果相同则会使用回调函数替换该key对应的value值,并将原来value进行返回;

2)如果不同,则判断当前位置是否是使用红黑树存,如果当前位置是使用红黑树存的,则会调用put红黑树的方法将该key与该红黑树下的key进行比对

                如果没有相同的key,则将该key,value存在红黑树下,

                如果该红黑树下存在相同的key则会把这个节点的对象返回,通过回调函数覆盖当前key                  对应的value值,并将原value值返回

3)如果当前位置不是使用红黑树,则会循环此位置的链表

        如果循环到链表的最后节点没有找到与与当前key值相同的key,则会使用使用尾插法将该key,value生成的node对象链入该链表,并且插入链表之后会判断该链表长度是不是已经超过了八个,如果超过了则会调佣treeifyBin(),在方法内会判断当前数组长度是否大于64,如果小于64的话会进行扩容,如果是大于64则会将该链表转成红黑树进行存储。

      如果循环到链表中找到了相同的key则会直接退出循环,并通过回调方法修改对应key的value值。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
HashMapJava中常用的一种数据结构,它基于哈希表实现。HashMap的底层由数组和链表(或红黑树)构成,主要包括数组、链表和红黑树三个部分。 1. 数组:HashMap内部维护了一个Node类型的数组,这个数组实际上是一个哈希表,用于存储键值对。数组的每个元素称为桶(bucket),每个桶可以存储一个或多个键值对。 2. 链表:当多个键值对被哈希到同一个桶时,它们会以链表的形式存储在该桶中。链表中的每个节点都包含了键、值以及指向下一个节点的指针。 3. 红黑树:为了提高HashMap的性能,在JDK1.8版本中引入了红黑树。当某个桶中的链表长度超过一定阈值(默认为8)时,链表将会转换为红黑树,以减少查找时间复杂度。 扩容机制是指当HashMap中存储的键值对数量超过了负载因子(默认为0.75)与当前数组容量的乘积时,HashMap会自动进行扩容操作。扩容后,HashMap会重新计算每个键值对在新数组中的位置,并将其放入新的桶中。 扩容过程中,HashMap会创建一个新的两倍大小的数组,并将原来数组中的元素重新分配到新数组中。这个过程涉及到重新哈希计算,即对键的哈希值进行重新计算,并通过取模运算确定新数组中的位置。在新数组中,键值对的顺序可能会发生改变。 扩容过程可能会比较耗时,因为需要重新计算哈希值和重新分配元素。但是扩容操作能够保证哈希表的负载因子维持在一个较低的水平,从而提高HashMap的性能和效率。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值