容器-HashMap添加元素、数组扩容的底层分析源码(十八)

容器-HashMap添加元素、数组扩容的底层分析源码(十八)

  1. 我们用map.put(),使用Ctrl+鼠标左键进入源代码,在put()方法中使用Ctrl+Alt选择HashMap接口实现类进入源代码,进行添加元素的分析。

    • 进入put()的源代码

      /**
           * Implements Map.put and related methods
           *
           * @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)//判断数组是否为空
                  n = (tab = resize()).length;//resize()方法,数组初始化、扩容
              if ((p = tab[i = (n - 1) & hash]) == null)//我们刚刚计算的哈希值 p=12,也就是判断我们的哈希值有没有元素
                  tab[i] = newNode(hash, key, value, null);//如果p有元素,这个就不执行了,就走else
              else {
              
              
                  Node<K,V> e; K k;//定义了两个局部变量
                  if (p.hash == hash &&//p调用的哈希值和新传进来的哈希值是否相等
                      ((k = p.key) == key || (key != null && key.equals(k))))
                      //也就是说,我们数组有一个12的索引,这个位置已经有一个节点了,新增的节点的Key和原先节点的Key相同了
                      
                      e = p;//把p赋值给e
                  else if (p instanceof TreeNode)//又要判断你这个p是否是一个树的节点
                      e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
                  //如果他是一个树了,就要往树上去挂节点
                  
                  else {
              
              //p不是一个树的节点,就不足else,因为满足了p调用的哈希值和新传进来的哈希值是否相等的if  ,如果索引12相同,但是Key不相同,则走的是这个Value,把新的节点挂接到老节点的后面                                                                                      
                      for (int binCount = 0; ; ++binCount) {
              
              
                          if ((e = p.next) == null) {
              
              //p.next为null,就是找到最后一个节点了
                              p.next = newNode(hash, key, value, null);
                              //把新节点挂在原来节点的后面
                              if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                                  //循环因子  TREEIFY_THRESHOLD是一个列表转树的一个域值,TREEIFY_THRESHOLD是8,还有一个条件就是数组的长度超过64,他才会去列表转成树,也就是下面那个 treeifyBin()的方法,我们来看下
                                  
                                  treeifyBin(tab, hash);
                              break;
                          }
                          //做节点的挂接
                          if (e.hash == hash &&
                              ((k = e.key) == key || (key != null && key.equals(k))))
                              break;
                          p = e;
                      }
                  }
                  //然后走这个if,这时e肯定是不为空的,就要做Value的替换了
                  if (e != null) {
              
               // existing mapping for key
                      V oldValue = e.value;//e调用的Value赋给了oldValue
                      if (!onlyIfAbsent || oldValue == null)
                          e.value = value;//新传进来的value又赋给了e调用的Value,这就体现了Value的替换,这就是Key相同完成了Value的覆盖
                      afterNodeAccess(e);
                      return oldValue;//把这个被替换掉的,老的Value返回
                  }
              }
              ++modCount;
              if (++size > threshold)
                  resize();
              afterNodeInsertion(evict);
              return null;
          }
      
      
    • 看下 treeifyBin(tab, hash)*;把链表做树形化的方法

       /**
           * 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;
              if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
                  //MIN_TREEIFY_CAPACITY是64,也就是当数组的长度小于64时,它不会去做链表的转换,而是去做数组的扩容
                  resize();//做数组的扩容
              //当数组的长度大于64,链表做树的转换
              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);
              }
          }
      
      
  2. 数组的扩容

    • 添加完元素以后,会对数组进行扩容操作,看到putval()方法的最后

      /**
           * Implements Map.put and related methods
           *
           * @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)//判断数组是否为空
                  n = (tab = resize()).length;//resize()方法,数组初始化、扩容
              if ((p = tab[i = (n - 1) & hash]) == null)//我们刚刚计算的哈希值 p=12,也就是判断我们的哈希值有没有元素
                  tab[i] = newNode(hash, key, value, null);//如果p有元素,这个就不执行了,就走else
              else {
              
              
                  Node<K,V> e; K k;//定义了两个局部变量
                  if (p.hash == hash &&//p调用的哈希值和新传进来的哈希值是否相等
                      ((k = p.key) == key || (key != null && key.equals(k))))
                      //也就是说,我们数组有一个12的索引,这个位置已经有一个节点了,新增的节点的Key和原先节点的Key相同了
                      
                      e = p;//把p赋值给e
                  else if (p instanceof TreeNode)//又要判断你这个p是否是一个树的节点
                      e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
                  //如果他是一个树了,就要往树上去挂节点
                  
                  else {
              
              //p不是一个树的节点,就不足else,因为满足了p调用的哈希值和新传进来的哈希值是否相等的if  ,如果索引12相同,但是Key不相同,则走的是这个Value,把新的节点挂接到老节点的后面                                                                                      
                      for (int binCount = 0; ; ++binCount) {
              
              
                          if ((e = p.next) == null) {
              
              //p.next为null,就是找到最后一个节点了
                              p.next = newNode(hash, key, value, null);
                              //把新节点挂在原来节点的后面
                              if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                                  //循环因子  TREEIFY_THRESHOLD是一个列表转树的一个域值,TREEIFY_THRESHOLD是8,还有一个条件就是数组的长度超过64,他才会去列表转成树,也就是下面那个 treeifyBin()的方法,我们来看下
                                  
                                  treeifyBin(tab, hash);
                              break;
                          }
                          //做节点的挂接
                          if (e.hash == hash &&
                              ((k = e.key) == key || (key != null && key.equals(k))))
                              break;
                          p = e;
                      }
                  }
                  //然后走这个if,这时e肯定是不为空的,就要做Value的替换了
                  if (e != null) {
              
               // existing mapping for key
                      V oldValue = e.value;//e调用的Value赋给了oldValue
                      if (!onlyIfAbsent || oldValue == null)
                          e.value = value;//新传进来的value又赋给了e调用的Value,这就体现了Value的替换,这就是Key相同完成了Value的覆盖
                      afterNodeAccess(e);
                      return oldValue;//把这个被替换掉的,老的Value返回
                  }
              }
              ++modCount; //记录当前哈希容器改变的次数的,你添加、删除元素都会记录
              if (++size > threshold)//判断数组是否要做扩容
                  //size记录当前节点的数量,threshold是一个扩容的域值,也就是数组的长度*扩容的负载因子,也就是16*0.75=12
                  resize();//进行扩容处理
              afterNodeInsertion(evict);
              return null;
          }
      
      
    • 我们继续看resize();的扩容处理

       /**
           * 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
           */
      //当前数组的容量是以2的容量来扩容的
          final Node<K,V>[] resize() {
              
              
              Node<K,V>[] oldTab = table;//table就是Node成员变量的数组
              int oldCap = (oldTab == null) ? 0 : oldTab.length;
              //oldTab现在肯定是不为空的,返回的是oldTab的数组长度
              int oldThr = threshold;//把扩容的域值赋给了oldThr
              int newCap, newThr = 0;//定义两个变量为0
              if (oldCap > 0) {
              
              //oldCap现在肯定是大于0的
                  if (oldCap >= MAXIMUM_CAPACITY) {
              
              
                      //判断oldCap是否大于最大上限值(MAXIMUM_CAPACITY)2的30次方
                      threshold = Integer.MAX_VALUE;
                      //如果达到最大上限值,把Integer的最大值赋给threshold
                      return oldTab; //然后返回oldTab,因为你已经到达最大容量了,没法在扩容了
                  }
                  //很显然,现在oldCap是不大于最大上限值的
                  else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                           oldCap >= DEFAULT_INITIAL_CAPACITY)
                      //newCap = oldCap << 1=16*2=32
                      // oldCap=16 = DEFAULT_INITIAL_CAPACITY=16,索引他们现在是相等的
                      
                      
                      newThr = oldThr << 1; // double threshold
                  //oldThr << 1 = threshold*2=12*2=24,所以newThr=24
              }
              else if (oldThr > 0) // initial capacity was placed in threshold
                  newCap = oldThr;
              //if满足,else就不走了
              else {
              
                             // zero initial threshold signifies using defaults
                  newCap = DEFAULT_INITIAL_CAPACITY;
                  newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
              }
             // newThr=24就不等于0,这个if也不走
              if (newThr == 0) {
              
              
                  float ft = (float)newCap * loadFactor;
                  newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                            (int)ft : Integer.MAX_VALUE);
              }
              threshold = newThr;//把新的扩容域值24赋给扩容因子,之前的扩容因子是12,现在变成24了
              
              @SuppressWarnings({
              
              "rawtypes","unchecked"})
              //new了一个数组,然后把newCap=32放入Node数组里面
                  Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
              table = newTab;//然后把新的数据赋给了table
              //oldTab等于之前的 table是16,是不为空的,继续走下面,就是把旧的数组的元素移到新的数组,做数组的移动
              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;
                              }
                          }
                      }
                  }
              }
              return newTab;//这样就把新的扩容数组返回回去了
          }
      

猜你喜欢

转载自blog.csdn.net/Xun_independent/article/details/114780038