赞
踩
在JDK 1.8 以前 HashMap 的实现是数组+链表,哈希函数很难保证元素的均匀分布。
当 HashMap 中有大量的元素都存放到同一个桶中时,这个桶下有一条长长的链表,这个时候 HashMap 就相当于一个单链表,假如单链表有 n 个元素,遍历的时间复杂度就是 O(n),完全失去了它的优势。
针对这种情况,JDK 1.8 中引入了 红黑树(查找时间复杂度为 O(logn))来优化这个问题。而红黑树的实现又交由内部类TreeNode实现。所以本文就hashmap中treenode的实现暂做分析。
treenode继承了LinkedHashMap.Entry,使其结构具有键值对特征,而其自身又通过私有属性构造出红黑树结构(父节点、左子节点、右子节点、是否红色、前驱结点),其中prev表示该节点在链表中的前驱结点以便删除时确定位置。
- static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
- TreeNode<K,V> parent; // 构建红黑树需要的父节点
- TreeNode<K,V> left;
- TreeNode<K,V> right;
- TreeNode<K,V> prev; //需要在删除后取消链接
- boolean red;
- TreeNode(int hash, K key, V val, Node<K,V> next) {//构造函数
- super(hash, key, val, next);
- }
可以看到该节点既有红黑树的特点又有双向链表的特征(有前驱,有后继),这样做是为了方便bucket结构在链表与红黑树之间进行转换。及jdk1.8中可能(注意是可能,至于什么时候出现根据hashmap中的阈值决定什么时候bucket为tree什么时候为链表)出现的结构为:
返回包含此节点所在的树的根节点
- final TreeNode<K,V> root() {
- for (TreeNode<K,V> r = this, p;;) {
- if ((p = r.parent) == null)//该节点的父节点为空则返回该节点
- return r;
- r = p;//父节点不为空则继续遍历
- }
- }
TreeNode在增加或删除节点后,都需要对整个树重新进行平衡,平衡之后的根节点也许就会发生变化,此时为了保证:如果HashMap元素数组根据下标取得的元素是一个TreeNode类型,那么这个TreeNode节点一定要是这颗树的根节点,同时也要是整个链表的首节点。
- /**
- * 把红黑树的根节点设为 其所在的数组槽 的第一个元素
- * 首先明确:TreeNode既是一个红黑树结构,也是一个双链表结构
- * 这个方法里做的事情,就是保证树的根节点一定也要成为链表的首节点
- */
- static <K,V> void moveRootToFront(Node<K,V>[] tab, TreeNode<K,V> root) {
- int n;
- if (root != null && tab != null && (n = tab.length) > 0) {
- int index = (n - 1) & root.hash; // 根据根节点的Hash值 和 HashMap的元素数组长度 取得根节点在数组中的位置
- TreeNode<K,V> first = (TreeNode<K,V>)tab[index]; // 首先取得该位置上的第一个节点对象
- if (root != first) {//如果根节点不是第一个结点
- Node<K,V> rn;
- tab[index] = root;//将结点集合中的相应位置换为根节点
- TreeNode<K,V> rp = root.prev;//记录根节点的前驱结点
- if ((rn = root.next) != null)//根节点的后继结点不为空
- ((TreeNode<K,V>)rn).prev = rp;//后继结点的前驱设为根节点的前驱
- if (rp != null)//前驱结点为空
- rp.next = rn;//前驱的后继
- if (first != null)
- first.prev = root;//第一个结点的前驱结点设为
- root.next = first;//根节点的后继为第一个结点
- root.prev = null;//前驱为空
- }
-
- // 在并发情况下进行递归运算时值是否会发生改变
- assert checkInvariants(root);
- }
- }
- /**
- *递归不变检查
- */
- static <K,V> boolean checkInvariants(TreeNode<K,V> t) {
- TreeNode<K,V> tp = t.parent, tl = t.left, tr = t.right,
- tb = t.prev, tn = (TreeNode<K,V>)t.next;
- if (tb != null && tb.next != t)
- return false;
- if (tn != null && tn.prev != t)
- return false;
- if (tp != null && t != tp.left && t != tp.right)
- return false;
- if (tl != null && (tl.parent != t || tl.hash > t.hash))
- return false;
- if (tr != null && (tr.parent != t || tr.hash < t.hash))
- return false;
- if (t.red && tl != null && tl.red && tr != null && tr.red)
- return false;
- if (tl != null && !checkInvariants(tl))
- return false;
- if (tr != null && !checkInvariants(tr))
- return false;
- return true;
- }
-

使用给定的hash和键查找从root p开始的树中的相应节点。 kc参数为键对象的class。对二叉树进行遍历,根据相应的hash值找到该键在二叉树中的位置,若查找到相应的位置,则在比较键值的大小,在比较时要注意该键对象是否实现了比较器,若实现了比较器,通过指定的CompareTo方法进行比较。
- final TreeNode<K,V> find(int h, Object k, Class<?> kc) {
- TreeNode<K,V> p = this;//获取树的根节点
- do {
- int ph, dir; K pk;
- TreeNode<K,V> pl = p.left, pr = p.right, q;
- if ((ph = p.hash) > h)//当前hash值小于指定hash值,遍历左子树
- p = pl;
- else if (ph < h)//若大于指定hash值,遍历右子树
- p = pr;
- else if ((pk = p.key) == k || (k != null && k.equals(pk)))//若键相等
- return p;
- else if (pl == null)//若左子树为空,遍历右子树
- p = pr;
- else if (pr == null)//右子树为空,遍历左子树
- p = pl;
- else if ((kc != null ||
- (kc = comparableClassFor(k)) != null) &&
- (dir = compareComparables(kc, k, pk)) != 0)
- p = (dir < 0) ? pl : pr;
- else if ((q = pr.find(h, k, kc)) != null)//若以查找过,则直接返回
- return q;
- else
- p = pl;
- } while (p != null);//若结点不为空
- return null;
- }
- /**
- *如果它的形式为“class C implements Comparable <C>”,则返回x的Class,否则返回null。
- *判断对象是否实现了比较器
- */
- static Class<?> comparableClassFor(Object x) {
- if (x instanceof Comparable) {
- Class<?> c; Type[] ts, as; Type t; ParameterizedType p;
- if ((c = x.getClass()) == String.class) // bypass checks
- return c;
- if ((ts = c.getGenericInterfaces()) != null) {
- for (int i = 0; i < ts.length; ++i) {
- if (((t = ts[i]) instanceof ParameterizedType) &&
- ((p = (ParameterizedType)t).getRawType() ==
- Comparable.class) &&
- (as = p.getActualTypeArguments()) != null &&
- as.length == 1 && as[0] == c) // type arg is c
- return c;
- }
- }
- }
- return null;
- }
-
- /**
- *如果x匹配kc(k的筛选可比类),则返回k.compareTo(x),否则返回0。
- */
- @SuppressWarnings({"rawtypes","unchecked"}) // for cast to Comparable
- static int compareComparables(Class<?> kc, Object k, Object x) {
- return (x == null || x.getClass() != kc ? 0 :
- ((Comparable)k).compareTo(x));
- }
-

定义插入规则。用于两个对象hashcode相等或者非比较的情况(该类没有实现比较器)下对两个对象的大小进行判断。若b的hashcode大于a的hashcode则放回1,否则返回-1.若两个类的类名不同或者两者都为空则返回0.
- static int tieBreakOrder(Object a, Object b) {
- int d;
- if (a == null || b == null ||
- (d = a.getClass().getName().
- compareTo(b.getClass().getName())) == 0)//类名相同,判断hashcode
- d = (System.identityHashCode(a) <= System.identityHashCode(b) ?
- -1 : 1);
- return d;
- }
前面我们提到,bucket中的元素超过一定阈值时,链表会进行重构形成红黑树,而小于阈值时,红黑树又回变成链表。
我们可以画一张示意图:
可以看到,当我们进行查找时,元素通过红黑树进行查找并不会因为链表结构影响了查询效率,而且这样做还有一个好处就是根节点如果做链表用可以直接获取到整个链表,避免了重新遍历红黑树形成链表的复杂性。
- /**
- * 将当前结点及其后链接的结点形成树
- * @return root of tree
- */
- final void treeify(Node<K,V>[] tab) {
- TreeNode<K,V> root = null;
- for (TreeNode<K,V> x = this, next; x != null; x = next) {
- next = (TreeNode<K,V>)x.next;
- x.left = x.right = null;
- if (root == null) { //首次进入循环,确定头结点,为黑色
- x.parent = null;
- x.red = false;
- root = x;
- }
- else { //后面进入循环走的逻辑,x 指向树中的某个节点
- K k = x.key;//获取键
- int h = x.hash;//获取hash
- Class<?> kc = null;//获取键类型
- for (TreeNode<K,V> p = root;;) {
- int dir, ph;
- K pk = p.key;
- if ((ph = p.hash) > h)//根节点大于当前hash值
- dir = -1;
- else if (ph < h)
- dir = 1;
- else if ((kc == null &&
- (kc = comparableClassFor(k)) == null) ||
- (dir = compareComparables(kc, k, pk)) == 0)
- dir = tieBreakOrder(k, pk);
-
- TreeNode<K,V> xp = p;
- if ((p = (dir <= 0) ? p.left : p.right) == null) {
- x.parent = xp;
- if (dir <= 0)
- xp.left = x;
- else
- xp.right = x;
- root = balanceInsertion(root, x);
- break;
- }
- }
- }
- }
- moveRootToFront(tab, root);
- }
- //返回一个非树列表,替换从该节点链接的列表。
- final Node<K,V> untreeify(HashMap<K,V> map) {
- Node<K,V> hd = null, tl = null;
- for (Node<K,V> q = this; q != null; q = q.next) {
- Node<K,V> p = map.replacementNode(q, null);
- if (tl == null)
- hd = p;
- else
- tl.next = p;
- tl = p;
- }
- return hd;
- }

左旋转示意图:
- //对root进行左旋转
- static <K,V> TreeNode<K,V> rotateLeft(TreeNode<K,V> root,
- TreeNode<K,V> p) {
- TreeNode<K,V> r, pp, rl;
- if (p != null && (r = p.right) != null) {//r为p的右子树
- if ((rl = p.right = r.left) != null)//rl为p的右子节点的左子树,并将其设为p的右子树
- rl.parent = p;//修改后的父节点为p
- if ((pp = r.parent = p.parent) == null)//p的右子树的父节点变为p的父节点
- (root = r).red = false;//若p为根节点,则为黑色
- else if (pp.left == p)//若p为根节点的左子树
- pp.left = r;//则根节点的左子树为p的右子树
- else
- pp.right = r;//否则将其右子树设为p.right
- r.left = p;//右子树的左子树为p
- p.parent = r;//p的父节点为p的右子树
- }
- return root;
- }

右旋转示意图:
- //对root结点进行右旋转
- static <K,V> TreeNode<K,V> rotateRight(TreeNode<K,V> root,
- TreeNode<K,V> p) {
- TreeNode<K,V> l, pp, lr;
- if (p != null && (l = p.left) != null) {
- if ((lr = p.left = l.right) != null)//p的左子树为左子树的右子树
- lr.parent = p;
- if ((pp = l.parent = p.parent) == null)
- (root = l).red = false;
- else if (pp.right == p)
- pp.right = l;
- else
- pp.left = l;
- l.right = p;
- p.parent = l;
- }
- return root;
- }
-

插入和删除元素后也要通过左旋转与右旋转进行树的平衡,只不过这两个平衡方法中定义了左旋和右旋的条件(红黑树插入和删除元素的三种情况),即根据颜色判断左旋还是右旋。
- //插入元素后进行平衡
- static <K,V> TreeNode<K,V> balanceInsertion(TreeNode<K,V> root,
- TreeNode<K,V> x) {
- x.red = true;//将插入节点设为红色
- for (TreeNode<K,V> xp, xpp, xppl, xppr;;) {
- if ((xp = x.parent) == null) {//父节点为空,设为黑色
- x.red = false;
- return x;
- }
- else if (!xp.red || (xpp = xp.parent) == null)//父节点的父节点为空,返回根节点
- return root;
- if (xp == (xppl = xpp.left)) {//若“z的父节点”是“z的祖父节点的左孩子”
- if ((xppr = xpp.right) != null && xppr.red) {//case1:叔叔是红色
- xppr.red = false;//将“叔叔节点”设为黑色
- xp.red = false;//将“父节点”设为黑色
- xpp.red = true;//将“祖父节点”设为“红色”。
- x = xpp;//将“祖父节点”设为“当前节点”(红色节点)
- }
- else {
- if (x == xp.right) {//Case 2条件:叔叔是黑色,且当前节点是右孩子
- root = rotateLeft(root, x = xp);// 以“新的当前节点”为支点进行左旋。
- xpp = (xp = x.parent) == null ? null : xp.parent;// 将“父节点”作为“新的当前节点”
- }
- if (xp != null) {//Case 3条件:叔叔是黑色,且当前节点是左孩子。
- xp.red = false;
- if (xpp != null) {
- xpp.red = true;//将“祖父节点”设为“红色”
- root = rotateRight(root, xpp);//以“祖父节点”为支点进行右旋
- }
- }
- }
- }
- else {// 若“z的父节点”是“z的祖父节点的右孩子”,将上面的操作中“right”和“left”交换位置
- if (xppl != null && xppl.red) {
- xppl.red = false;
- xp.red = false;
- xpp.red = true;
- x = xpp;
- }
- else {
- if (x == xp.left) {
- root = rotateRight(root, x = xp);
- xpp = (xp = x.parent) == null ? null : xp.parent;
- }
- if (xp != null) {
- xp.red = false;
- if (xpp != null) {
- xpp.red = true;
- root = rotateLeft(root, xpp);
- }
- }
- }
- }
- }
- }
- //删除元素进行平衡
- static <K,V> TreeNode<K,V> balanceDeletion(TreeNode<K,V> root,
- TreeNode<K,V> x) {
- for (TreeNode<K,V> xp, xpl, xpr;;) {
- if (x == null || x == root)//若为根节点,直接返回
- return root;
- else if ((xp = x.parent) == null) {//若x的父节点为空
- x.red = false;//设为黑色
- return x;
- }
- else if (x.red) {//若为红色
- x.red = false;
- return root;
- }
- else if ((xpl = xp.left) == x) {// 若 “x”是“它父节点的左孩子”
- if ((xpr = xp.right) != null && xpr.red) {//Case 1: x是“黑+黑”节点,x的兄弟节点是红色
- xpr.red = false;// 将x的兄弟节点设为“黑色”
- xp.red = true;//将x的父节点设为“红色”。
- root = rotateLeft(root, xp);//对x的父节点进行左旋。
- xpr = (xp = x.parent) == null ? null : xp.right;//左旋后,重新设置x的兄弟节点。
- }
- if (xpr == null)
- x = xp;
- else {
- TreeNode<K,V> sl = xpr.left, sr = xpr.right;
- if ((sr == null || !sr.red) &&
- (sl == null || !sl.red)) {//Case 2: x是“黑+黑”节点,x的兄弟节点是黑色,x的兄弟节点的两个孩子都是黑色
- xpr.red = true;//将x的兄弟节点设为“红色”。
- x = xp;//设置“x的父节点”为“新的x节点”。
- }
- else {
- if (sr == null || !sr.red) {//Case 3: x是“黑+黑”节点,x的兄弟节点是黑色;x的兄弟节点的左孩子是红色,右孩子是黑色的
- if (sl != null)
- sl.red = false;//将x兄弟节点的左孩子设为“黑色”。
- xpr.red = true;//将x兄弟节点设为“红色”。
- root = rotateRight(root, xpr);//对x的兄弟节点进行右旋。
- xpr = (xp = x.parent) == null ?
- null : xp.right;
- }
- //Case 4:x是“黑+黑”节点,x的兄弟节点是黑色;x的兄弟节点的右孩子是红色的。(01) 将x父节点颜色 赋值给 x的兄弟节点。
- if (xpr != null) {
- xpr.red = (xp == null) ? false : xp.red;//将x兄弟节点的右子节设为“黑色”。
- if ((sr = xpr.right) != null)
- sr.red = false;
- }
- if (xp != null) {
- xp.red = false;//将x父节点设为“黑色”。
- root = rotateLeft(root, xp);//对x的父节点进行左旋。
- }
- x = root;
- }
- }
- }
- else { //若 “x”是“它父节点的右孩子”,将上面的操作中“right”和“left”交换位置,然后依次执行。
- if (xpl != null && xpl.red) {
- xpl.red = false;
- xp.red = true;
- root = rotateRight(root, xp);
- xpl = (xp = x.parent) == null ? null : xp.left;
- }
- if (xpl == null)
- x = xp;
- else {
- TreeNode<K,V> sl = xpl.left, sr = xpl.right;
- if ((sl == null || !sl.red) &&
- (sr == null || !sr.red)) {
- xpl.red = true;
- x = xp;
- }
- else {
- if (sl == null || !sl.red) {
- if (sr != null)
- sr.red = false;
- xpl.red = true;
- root = rotateLeft(root, xpl);
- xpl = (xp = x.parent) == null ?
- null : xp.left;
- }
- if (xpl != null) {
- xpl.red = (xp == null) ? false : xp.red;
- if ((sl = xpl.left) != null)
- sl.red = false;
- }
- if (xp != null) {
- xp.red = false;
- root = rotateRight(root, xp);
- }
- x = root;
- }
- }
- }
- }
- }
-

向红黑树中插入元素。首先根据键值对的hash值判断其是否存在,然后再将值插入到红黑树中,插入完毕后调用balanceInsertion()方法进行平衡插入操作。
删除红黑树中的元素时也要进行删除后树的平衡操作。
- final TreeNode putTreeVal(HashMap map, Node[] tab,
- int h, K k, V v) {
- Class kc = null;
- boolean searched = false;
- TreeNode root = (parent != null) ? root() : this;
- //每次添加元素时,从根节点遍历,对比哈希值
- for (TreeNode p = root;;) {
- int dir, ph; K pk;
- if ((ph = p.hash) > h)
- dir = -1;
- else if (ph < h)
- dir = 1;
- else if ((pk = p.key) == k || (k != null && k.equals(pk)))
- //如果当前节点的哈希值、键和要添加的都一致,就返回当前节点
- return p;
- else if ((kc == null &&
- (kc = comparableClassFor(k)) == null) ||
- (dir = compareComparables(kc, k, pk)) == 0) {
- //如果当前节点和要添加的节点哈希值相等,但是两个节点的键不是一个类,只好去挨个对比左右孩子
- if (!searched) {
- TreeNode q, ch;
- searched = true;
- if (((ch = p.left) != null &&
- (q = ch.find(h, k, kc)) != null) ||
- ((ch = p.right) != null &&
- (q = ch.find(h, k, kc)) != null))
- //如果从 ch 所在子树中可以找到要添加的节点,就直接返回
- return q;
- }
- //哈希值相等,但键无法比较,只好通过特殊的方法给个结果
- dir = tieBreakOrder(k, pk);
- }
-
- //经过前面的计算,得到了当前节点和要插入节点的一个大小关系
- //要插入的节点比当前节点小就插到左子树,大就插到右子树
- TreeNode xp = p;
- //这里有个判断,如果当前节点还没有左孩子或者右孩子时才能插入,否则就进入下一轮循环
- if ((p = (dir <= 0) ? p.left : p.right) == null) {
- Node xpn = xp.next;
- TreeNode x = map.newTreeNode(h, k, v, xpn);
- if (dir <= 0)
- xp.left = x;
- else
- xp.right = x;
- xp.next = x;
- x.parent = x.prev = xp;
- if (xpn != null)
- ((TreeNode)xpn).prev = x;
- //红黑树中,插入元素后必要的平衡调整操作
- moveRootToFront(tab, balanceInsertion(root, x));
- return null;
- }
- }
- }
- //删除树节点
- final void removeTreeNode(HashMap<K,V> map, Node<K,V>[] tab,
- boolean movable) {
- int n;
- if (tab == null || (n = tab.length) == 0)
- return;
- int index = (n - 1) & hash;//查找数组下标
- TreeNode<K,V> first = (TreeNode<K,V>)tab[index], root = first, rl;
- TreeNode<K,V> succ = (TreeNode<K,V>)next, pred = prev;
- if (pred == null)
- tab[index] = first = succ;
- else
- pred.next = succ;
- if (succ != null)
- succ.prev = pred;
- if (first == null)
- return;
- if (root.parent != null)
- root = root.root();//获取根节点
- if (root == null || root.right == null ||
- (rl = root.left) == null || rl.left == null) {
- tab[index] = first.untreeify(map); // 过小
- return;
- }
- TreeNode<K,V> p = this, pl = left, pr = right, replacement;
- if (pl != null && pr != null) {
- TreeNode<K,V> s = pr, sl;
- while ((sl = s.left) != null) // 成功找到该元素
- s = sl;
- boolean c = s.red; s.red = p.red; p.red = c; // 交换眼色
- TreeNode<K,V> sr = s.right;
- TreeNode<K,V> pp = p.parent;
- if (s == pr) { // p是s的直接父节点
- p.parent = s;
- s.right = p;
- }
- else {
- TreeNode<K,V> sp = s.parent;
- if ((p.parent = sp) != null) {
- if (s == sp.left)
- sp.left = p;
- else
- sp.right = p;
- }
- if ((s.right = pr) != null)
- pr.parent = s;
- }
- p.left = null;
- if ((p.right = sr) != null)
- sr.parent = p;
- if ((s.left = pl) != null)
- pl.parent = s;
- if ((s.parent = pp) == null)
- root = s;
- else if (p == pp.left)
- pp.left = s;
- else
- pp.right = s;
- if (sr != null)
- replacement = sr;
- else
- replacement = p;
- }
- else if (pl != null)
- replacement = pl;
- else if (pr != null)
- replacement = pr;
- else
- replacement = p;
- if (replacement != p) {
- TreeNode<K,V> pp = replacement.parent = p.parent;
- if (pp == null)
- root = replacement;
- else if (p == pp.left)
- pp.left = replacement;
- else
- pp.right = replacement;
- p.left = p.right = p.parent = null;
- }
-
- TreeNode<K,V> r = p.red ? root : balanceDeletion(root, replacement);
-
- if (replacement == p) { //
- TreeNode<K,V> pp = p.parent;
- p.parent = null;
- if (pp != null) {
- if (p == pp.left)
- pp.left = null;
- else if (p == pp.right)
- pp.right = null;
- }
- }
- if (movable)
- moveRootToFront(tab, r);
- }
-

当扩容时,如果当前桶中元素结构是红黑树,并且元素个数小于链表还原阈值 UNTREEIFY_THRESHOLD (默认为 6),就会把桶中的树形结构缩小或者直接还原(切分)为链表结构。
- final void split(HashMap map, Node[] tab, int index, int bit) {
- TreeNode b = this;
- TreeNode loHead = null, loTail = null;
- TreeNode hiHead = null, hiTail = null;
- int lc = 0, hc = 0;
- for (TreeNode e = b, next; e != null; e = next) {
- next = (TreeNode)e.next;
- e.next = null;
- //如果当前节点哈希值的最后一位等于要修剪的 bit 值
- if ((e.hash & bit) == 0) {
- //就把当前节点放到 lXXX 树中
- if ((e.prev = loTail) == null)
- loHead = e;
- else
- loTail.next = e;
- //然后 loTail 记录 e
- loTail = e;
- //记录 lXXX 树的节点数量
- ++lc;
- }
- else { //如果当前节点哈希值最后一位不是要修剪的
- //就把当前节点放到 hXXX 树中
- if ((e.prev = hiTail) == null)
- hiHead = e;
- else
- hiTail.next = e;
- hiTail = e;
- //记录 hXXX 树的节点数量
- ++hc;
- }
- }
-
-
- if (loHead != null) {
- if (lc <= UNTREEIFY_THRESHOLD)//变为链表
- tab[index] = loHead.untreeify(map);
- else {
- //否则让索引位置的结点指向 lXXX 树,这个树被修剪过,元素少了
- tab[index] = loHead;
- if (hiHead != null) // (else is already treeified)
- loHead.treeify(tab);
- }
- }
- if (hiHead != null) {
- if (hc <= UNTREEIFY_THRESHOLD)
- tab[index + bit] = hiHead.untreeify(map);
- else {
- tab[index + bit] = hiHead;
- if (loHead != null)
- hiHead.treeify(tab);
- }
- }
- }

文章参考:Java 集合深入理解(17):HashMap 在 JDK 1.8 后新增的红黑树结构_张拭心的博客 shixinzhang-CSDN博客_hashmap1.8红黑树
红黑树的插入与删除_朱广健的博客-CSDN博客_红黑树删除时间复杂度
具体的treenode方法到此已经看完啦,这里只是bucket(bin)中的结构变化,具体hashmap实现看: JDK1.8源码解析-HashMap
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。