jdk8版HashMap红黑树学习笔记

0x00.新老HashMap区别

本文使用jdk7(1.7.0_79)与 jdk8(1.8.0_45)进行对比,主要学习数据结构区别

数据结构

jdk7内部数据结构为数组+链表,通过key的hash值计算数据所在数组下标,多个key的hash相同或hash计算的数组下标相同,但是key值不同时,往链表尾追加Entry。

transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE;
static class Entry<K,V> implements Map.Entry<K,V> {
    final K key;
    V value;
    Entry<K,V> next;
    int hash;
}

jdk8内部数据结构为数组+(链表 或 红黑树),通过key的hash值计算数据所在数组下标,多个key的hash相同或hash计算的数组下标相同,但是key值不同时,检查节点是否为树节点,是树节点则往树节点添加,如果是普通节点则往链表尾追加Entry,当链表长度大于8时,则将链表转为红黑树。

transient Node<K,V>[] table;
static class Node<K,V> implements Map.Entry<K,V> {
    final int hash;
    final K key;
    V value;
    Node<K,V> next;
}
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;
}
//LinkedHashMap.Entry
static class Entry<K,V> extends HashMap.Node<K,V> {
    Entry<K,V> before, after;
    Entry(int hash, K key, V value, Node<K,V> next) {
        super(hash, key, value, next);
    }
}

0x01. HashMap.put源码阅读

源码学习,边看源码边加注释,边debug,边理解。

public V put(K key, V value) {
    return putVal(hash(key), key, value, false, true);
}
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)
        //当HashMap的内部table为空时,触发resize()
        n = (tab = resize()).length;
    if ((p = tab[i = (n - 1) & hash]) == null)
        //当通过key的hash值计算数据所在数组下标值为null时直接生成新节点放入桶
        tab[i] = newNode(hash, key, value, null);
    else {
        Node<K,V> e; K k;
        if (p.hash == hash &&
            ((k = p.key) == key || (key != null && key.equals(k))))
            //key完全相同
            e = p;
        else if (p instanceof TreeNode)
            //桶内对象已经时红黑树
            e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
        else {
            //桶内已经存在普通节点则遍历链表,往链表尾部添加节点
            for (int binCount = 0; ; ++binCount) {
                if ((e = p.next) == null) { //第1个循环是获取第2个节点了(0->root.next)
                    //binCount为0时插入的第二个节点
                    p.next = newNode(hash, key, value, null);
                    //如果链表内的数据已经超过8个则将链表转成红黑树
                    if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                        //binCount等于7时插入的第9个节点
                        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();
    afterNodeInsertion(evict);
    return null;
}
final void treeifyBin(Node<K,V>[] tab, int hash) {
    int n, index; Node<K,V> e;
    //检查tab的长度是否大于等于64,小于则扩容
    if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
        resize();
    else if ((e = tab[index = (n - 1) & hash]) != null) {
        //将Node对象转为TreeNode
        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)
            //将TreeNode链表转成红黑树
            hd.treeify(tab);
    }
}
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) {
            //root为空时直接第一个元素存入root
            x.parent = null;
            x.red = false;
            root = x;
        }
        else {
            K k = x.key;
            int h = x.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)//优先直接比较hash值
                    dir = 1;
                else if ((kc == null &&
                          (kc = comparableClassFor(k)) == null) || //hash值相同则判断key是否实现Comparable接口
                         (dir = compareComparables(kc, k, pk)) == 0) //实现了Comparable接口则直接比较
                    //没有实现Comparable接口则用System.identityHashCode比较
                    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;
                }
            }
        }
    }
    //将root接口放入table的第一个元素
    moveRootToFront(tab, 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) {
            //则当前节点为root 直接将颜色设置为黑色 
            x.red = false;
            return x;
        }
        else if (!xp.red || (xpp = xp.parent) == null)
            //当前节点父节点为黑色节点 或者当前节点的父节点时root节点
            return root;
        if (xp == (xppl = xpp.left)) {//当前节点的父节点是左子节点(父节点为红色节点)
            if ((xppr = xpp.right) != null && xppr.red) {
                //当前节点的父节点以及父节点的兄弟节点都是红色 则颜色反转
                xppr.red = false;
                xp.red = false;
                xpp.red = true;
                x = xpp;
            }
            else {
                //当前节点为右节点 则先进行左旋
                if (x == xp.right) {
                    root = rotateLeft(root, x = xp);
                    xpp = (xp = x.parent) == null ? null : xp.parent;
                }
                //父节点不为空 则变色 右旋
                if (xp != null) {
                    xp.red = false;
                    if (xpp != null) {
                        xpp.red = true;
                        root = rotateRight(root, xpp);
                    }
                }
            }
        }
        else {//当前节点的父节点是右子节点
            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);
                    }
                }
            }
        }
    }
}

0x02. 测试代码

触发链表转红黑树的测试代码 可直接用来debug

import java.util.HashMap;

/**
 * Created by qiyan on 2017/4/9.
 */
public class HashMapTest {
    public static void main(String[] args) throws Exception {
        //map内的数组容量大于等于64 且 链表数量大于8才会进行红黑树转换
        HashMap map = new HashMap(64);
        for (int i = 0; i <= 8; i++) {
            map.put(new HashCodeOneObj(i), i);
        }
        System.out.println(map);
    }

    private static class HashCodeOneObj implements Comparable<HashCodeOneObj> {
        private int val;

        public HashCodeOneObj(int val) {
            this.val = val;
        }

        public int getVal() {
            return val;
        }

        @Override
        public int hashCode() {
            return 1; //让所有数据都存入一个桶
        }

        @Override
        public int compareTo(HashCodeOneObj o) {
            if (null == o) {
                return -1;
            }
            return Integer.compare(this.getVal(), o.getVal());
        }
    }
}

链表转红黑树过程示意图:

《jdk8版HashMap红黑树学习笔记》 红黑树v2(insert-0-8).png
《jdk8版HashMap红黑树学习笔记》 HashMap中的红黑树

    原文作者:qiyanjs
    原文地址: https://www.jianshu.com/p/814432ed04e8
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞