加入收藏 | 设为首页 | 会员中心 | 我要投稿 济南站长网 (https://www.0531zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 运营中心 > 建站资源 > 优化 > 正文

3分钟让你明白:HashMap之红黑树树化过程

发布时间:2019-10-14 08:48:32 所属栏目:优化 来源:追逐仰望星空
导读:副标题#e# 01 概述 HashMap是Java程序员使用频率最高的用于映射(键值对)处理的数据类型。随着JDK(Java Developmet Kit)版本的更新,JDK1.8对HashMap底层的实现进行了优化,例如引入红黑树的数据结构和扩容的优化等。本文主要分析一下HashMap中红黑树树化的

上面的方法通过hash计算插入的项的槽位,如果有是一样的key则根据设置的参数是否执行覆盖,如果相应槽位空的话直接插入,如果对应的槽位有项则判断是红黑树结构还是链表结构的槽位,链表的话则顺着链表寻找如果找到一样的key则根据参数选择覆盖,没有找到则链接在链表最后面,链表项的数目大于8则对其进行树化,如果是红黑树结构则按照树的添加方式添加项。

让我们看一下treeifyBin这个方法。

  1. final void treeifyBin(Node<K, V>[] tab, int hash) 
  2.  { 
  3.  int n, index; 
  4.  Node<K, V> e; 
  5.  if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY) 
  6.  // resize()方法这里不过多介绍,感兴趣的可以去看上面的链接。 
  7.  resize(); 
  8.  // 通过hash求出bucket的位置。 
  9.  else if ((e = tab[index = (n - 1) & hash]) != null) 
  10.  { 
  11.  TreeNode<K, V> hd = null, tl = null; 
  12.  do 
  13.  { 
  14.  // 将每个节点包装成TreeNode。 
  15.  TreeNode<K, V> p = replacementTreeNode(e, null); 
  16.  if (tl == null) 
  17.  hd = p; 
  18.  else 
  19.  { 
  20.  // 将所有TreeNode连接在一起此时只是链表结构。 
  21.  p.prev = tl; 
  22.  tl.next = p; 
  23.  } 
  24.  tl = p; 
  25.  } while ((e = e.next) != null); 
  26.  if ((tab[index] = hd) != null) 
  27.  // 对TreeNode链表进行树化。 
  28.  hd.treeify(tab); 
  29.  } 
  30.  } 

找个方法所做的事情就是将刚才九个项以链表的方式连接在一起,然后通过它构建红黑树。

看代码之前我们先了解一下TreeNode

  1. static final class TreeNode<K, V> extends LinkedHashMap.Entry<K, V> 
  2.  { 
  3.  TreeNode<K, V> parent; // red-black tree links 
  4.  TreeNode<K, V> left; 
  5.  TreeNode<K, V> right; 
  6.  TreeNode<K, V> prev; // needed to unlink next upon deletion 
  7.  boolean red; 
  8.  TreeNode(int hash, K key, V val, Node<K, V> next) 
  9.  { 
  10.  super(hash, key, val, next); 
  11.  } 
  12.   
  13.  final void treeify(Node<K,V>[] tab) 
  14.  { 
  15.  // ...... 
  16.  } 
  17.   
  18.  static <K,V> TreeNode<K,V> balanceInsertion(TreeNode<K,V> root, TreeNode<K,V> x) 
  19.  { 
  20.  // ...... 
  21.  } 
  22.   
  23.  static <K,V> TreeNode<K,V> rotateLeft(TreeNode<K,V> root, TreeNode<K,V> p) 
  24.  { 
  25.  // ...... 
  26.  } 
  27.   
  28.  static <K,V> TreeNode<K,V> rotateRight(TreeNode<K,V> root, TreeNode<K,V> p) 
  29.  { 
  30.  // ...... 
  31.  } 
  32.   
  33.  // ......其余方法省略 
  34.  } 

可以看出出真正的维护红黑树结构的方法并没有在HashMap中,全部都在TreeNode类内部。

(编辑:济南站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!