集合-HashMap源码解析

本文深入解析HashMap的底层数据结构、工作原理及源码实现。详细介绍了HashMap如何通过数组、链表和红黑树来存储和检索键值对,涵盖了元素添加、查找、移除、扩容等核心操作。

如同说到List,我们想到的是ArrayList,Map中我们用的最多的就是HashMap,HashMap拥有和ArrayList同等重要的地位。ArrayList是单列集合,存储的是一种类型的的值(泛型类型不为Object情况)。HashMap是双列集合,存储的key-value的键值对。从本质上说,HashMap和Java Bean对象是一致的,key对应的是属性,value对应的是属性值。HashMap底层的数据结构较为复杂,涉及到了数组、链表、红黑树知识,如果对相关知识不太熟悉,可以先看看ArrayListLinkedListTreeMap的源码解析。

1.接口实现

可拷贝、可序列化、Map实现类

2.成员变量

//默认初始容量16,map容量必须为2的n次方。
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;

//链表转红黑色阈值
static final int TREEIFY_THRESHOLD = 8;

//红黑树转链表阈值
static final int UNTREEIFY_THRESHOLD = 6;

//Node数组,存储元素
transient Node<K,V>[] table;

//map中元素个数
transient int size;

//map结构修改次数
transient int modCount;

//扩容阈值
int threshold;

//加载因子,默认0.75
final float loadFactor;
    //单链表节点,链表的插入采用的是尾插法
    static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        V value;
        Node<K,V> next;
    }


    //红黑树节点,继承了Node节点
    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;
    }

数据结构:数组+链表(单链表尾插法)+红黑树

3.构造方法

    //空构造,加载因子设置为默认值0.75f    
    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }

    //指定容量和加载因子
    public HashMap(int initialCapacity, float loadFactor) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " +
                                               initialCapacity);
        if (initialCapacity > MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal load factor: " +
                                               loadFactor);
        this.loadFactor = loadFactor;
        //找到一个大于且最接近initialCapacity值的2的n次方数。
        this.threshold = tableSizeFor(initialCapacity);
    }

    //指定容量,加载因子使用默认值
    public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }

    //map容器转换,将元素从map实现类m中存到hashMap中
    public HashMap(Map<? extends K, ? extends V> m) {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        //可能涉及到hashMap的初始化,扩容,元素添加过程等
        putMapEntries(m, false);
    }

4.元素添加

    //元素添加    
    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

    //计算key的hash值,使用的是key的hashCode的高16位和低16位异或,充分使用key的hashCode值
    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }
    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;
        if ((p = tab[i = (n - 1) & hash]) == null)
            //若索引位置的首节点p为空,直接插入元素
            tab[i] = newNode(hash, key, value, null);
        else {
            //索引位置的首节点p不为空
            Node<K,V> e; K k;
            //判断首节点p和待插入的key是否相同
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            else if (p instanceof TreeNode)
                //首节点p是树节点,进行树节点的插入操作,先查找父节点,插入后进行自平衡操作
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
                //首节点p是链表节点,binCount是索引i处的节点数
                for (int binCount = 0; ; ++binCount) {
                    //遍历链表结构,看key值是否已存在,p.next表示取链表的下一个节点。
                    if ((e = p.next) == null) {
                        //遍历到链表的最后一个节点都没有找到key,表示key不存在,
                        //直接插入一个新的节点,尾插法,即在链表的最后插入节点。                                                      
                        p.next = newNode(hash, key, value, null);
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            //当索引i处的节点数大于树化阈值时,链表转红黑树
                            treeifyBin(tab, hash);
                        break;
                    }
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        //key值已存在
                        break;
                    p = e;
                }
            }
            //找到了key值,将vlaue替换为新值
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                //hashMap的空实现,适用于LinkedHashMap
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        //当数组中元素个数大于扩容阈值时,扩容
        if (++size > threshold)
            resize();
        //hashMap的空实现,适用于LinkedHashMap
        afterNodeInsertion(evict);
        return null;
    }
        //map中树结构添加元素
        final TreeNode<K,V> putTreeVal(HashMap<K,V> map, Node<K,V>[] tab,
                                       int h, K k, V v) {
            Class<?> kc = null;
            boolean searched = false;
            //查找根节点
            TreeNode<K,V> root = (parent != null) ? root() : this;
            for (TreeNode<K,V> p = root;;) {
                int dir, ph; K pk;
                //p的hash值大于key的hash值,往p的左子树找
                if ((ph = p.hash) > h)
                    dir = -1;
                //p的hash值大于key的hash值,往p的右子树找
                else if (ph < h)
                    dir = 1;
                //p的hash值等于key的hash值,且equals方法相等,返回p
                else if ((pk = p.key) == k || (k != null && k.equals(pk)))
                    return p;
                //p的hash值等于key的hash值,且equals方法不相等
                else if ((kc == null &&
                          (kc = comparableClassFor(k)) == null) ||
                         (dir = compareComparables(kc, k, pk)) == 0) {
                    if (!searched) {
                        TreeNode<K,V> 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))
                            return q;
                    }
                    //设定一个规则,规定当前节点和待插入节点的顺序
                    dir = tieBreakOrder(k, pk);
                }

                //xp为插入节点的父节点
                TreeNode<K,V> xp = p;
                if ((p = (dir <= 0) ? p.left : p.right) == null) {
                    //新增插入节点x,x的父节点为xp
                    //插入节点x之前xp的下一个节点是xpn即xp xpn
                    //插入节点x之后 xp x xpn
                    Node<K,V> xpn = xp.next;
                    TreeNode<K,V> 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<K,V>)xpn).prev = x;
                    //将树的root节点设置为桶中索引的第一个节点即table[index]=root
                    moveRootToFront(tab, balanceInsertion(root, x));
                    return null;
                }
            }
        }

1.map中若节点数组未初始化,则进行初始化操作。

2.若没有hash碰撞,直接插入节点。

3.若发生碰撞,首先检查桶中指定索引处的第一个元素是否和插入的元素相同。相同则结束。

4.若节点是树节点,则进行红黑树的插入操作。先查找父节点,然后插入后做自平衡。

5.若节点是链表节点,逐个节点遍历看key是否已存在,存在则结束,否则使用尾插法生成新的节点,插入后若链表的节点达到阈值8,进行树化操作,链表转红黑树。

6.若key值存在,更新对应的value值。

7.插入节点后的节点数size若大于扩容阈值threshold,进行扩容。

5.元素查找

    public V get(Object key) {
        Node<K,V> e;
        //根据key找到对应的节点
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }

    final Node<K,V> getNode(int hash, Object key) {
        Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {
            //先检查key所在索引位置的第一个节点,看是否是要查找的节点
            if (first.hash == hash && // always check first node
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
            //第一个节点未找到,看下一个节点
            if ((e = first.next) != null) {
                if (first instanceof TreeNode)
                    //树结构,按照树结构的方式查找
                    return ((TreeNode<K,V>)first).getTreeNode(hash, key);
                do {
                    //链表结构,遍历查找
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        //table为空,直接返回
        return null;
    }

1.检查查找的key与其所在桶中位置的第一个元素是否相等。相等则返回。

2.若节点是红黑树,则进入红黑树的查找算法。红黑树的查找算法:从根节点开始,设置根节点为当前节点p。若p的hash大于查找节点key的hash,则向p的左子树查找,左子树设置为p;若p的hash小于查找节点key的hash,则向p的右子树查找,右子树设置为p。若p的hash等于查找节点key的hash(且key的equals方法相等),则p为要查找的节点。若p的hash为null,则返回要查找的节点不存在。

3.若节点是链表则进行链表的查找。

6.元素移除

    public V remove(Object key) {
        Node<K,V> e;
        return (e = removeNode(hash(key), key, null, false, true)) == null ?
            null : e.value;
    }

    final Node<K,V> removeNode(int hash, Object key, Object value,
                               boolean matchValue, boolean movable) {
        //index为key在数组的索引位置
        Node<K,V>[] tab; Node<K,V> p; int n, index;
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (p = tab[index = (n - 1) & hash]) != null) {
            //node表示要删除的节点
            Node<K,V> node = null, e; K k; V v;
    
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                //index首节点就是要找的节点
                node = p;
            //index首节点不是要找的节点,继续看下一个节点
            else if ((e = p.next) != null) {
                
                if (p instanceof TreeNode)
                    //树结构,按红黑树的查找方式查找要删除的节点
                    node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
                else {
                    //链表结构,遍历查找要删除的节点
                    do {
                        if (e.hash == hash &&
                            ((k = e.key) == key ||
                             (key != null && key.equals(k)))) {
                            node = e;
                            break;
                        }
                        p = e;
                    } while ((e = e.next) != null);
                }
            }
            if (node != null && (!matchValue || (v = node.value) == value ||
                                 (value != null && value.equals(v)))) {
                //找到了要删除的节点node
                //若节点类型是树节点,按树节点方式移除
                if (node instanceof TreeNode)
                    ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
                //节点类型是链表节点
                else if (node == p)
                    //在链表的首节点出找到,删除后,则首节点指向node的后一个节点。
                    tab[index] = node.next;
                else
                    //链表遍历的时候找到node节点,p为node的前一个节点,node节点删除后
                    //p的下一个节点指向node的下一个节点。
                    p.next = node.next;
                ++modCount;
                --size;
                //hashMap的空实现,适用于LinkedHashMap
                afterNodeRemoval(node);
                return node;
            }
        }
        //table为空,或者key所在索引为的节点为空
        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;
            //设删除节点为node,first表示索引index处的第一个元素,也即根节点,
            //rl是根节点的左子树
            TreeNode<K,V> first = (TreeNode<K,V>)tab[index], root = first, rl;
            //next为node节点的下一个元素,pred为node节点的上一个元素
            TreeNode<K,V> succ = (TreeNode<K,V>)next, pred = prev;

            //修正node的节点链表引用关系
            if (pred == null)
                //node是根节点
                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);  // too small
                return;
            }
            //p为删除节点,同node。查找替换节点,可参考treeMap的移除过程,一共存在5中场景
            TreeNode<K,V> p = this, pl = left, pr = right, replacement;
            if (pl != null && pr != null) {
                //p有两个子节点,则p的右子树的最左子节点为替换节点
                TreeNode<K,V> s = pr, sl;
                while ((sl = s.left) != null) // find successor
                    s = sl;
                boolean c = s.red; s.red = p.red; p.red = c; // swap colors
                TreeNode<K,V> sr = s.right;
                TreeNode<K,V> pp = p.parent;
                //交换删除节点p和替换节点s的引用

                //p是s的直接父节点,即p的右子树没有左子节点,但可能存在右子节点
                if (s == pr) { // p was s's direct parent
                    p.parent = s;
                    s.right = p;
                }
                else {
                    //p不是s的直接父节点,即p的右子树有左子节点,最左子节点可能也存在右子节点
                    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)
                    //场景2,删除节点p的右子树的最左子节点存在右子节点,即替换节点不是叶子节
                    //点,将该右子节点sr设置为替换节点
                    //此时p和s的引用已交换完成,p继续作为删除节点,sr作为它的替换节点
                    replacement = sr;
                else
                    //场景1,删除节点p的右子树的最左子节点是替换节点
                    replacement = p;
            }
            else if (pl != null)
                //场景3,p只有一个左子节点,则左子节点为替换节点
                replacement = pl;
            else if (pr != null)
                //场景4,p只有一个右子节点,则右子节点为替换节点
                replacement = pr;
            else
                //场景5,p没有子节点,则p节点为替换节点
                replacement = p;
            if (replacement != p) {
                //场景2,3,4进入
                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) {  // detach
                //场景1,5进入
                //替换节点没有子节点
                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);
        }

1.首先需要找到要移除的节点node。检查查找的key与其所在桶中位置的第一个元素是否相等。相等则node为第一个节点。

2.不相等则按照红黑树或者链表结构找到需要删除的节点。

3.若删除的节点类型是树节点,首先找到替换节点,更新删除节点和替换节点的相关引用(parent、left、right),然后做自平衡操作。

4.若删除节点是链表节点,若删除节点是桶中的第一个元素,则桶中首节点引用指向删除节点的下一个节点。否则使删除节点的前一个节点指向删除节点的下一个节点。

5.更新map结构变更次数modCount和map键值对数size。

7.扩容

    //table初始化或者扩容    
    final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table;
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        int oldThr = threshold;
        int newCap, newThr = 0;
        if (oldCap > 0) {
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            //扩容,数组长度变为原来的2倍,扩容阈值变为原来的2倍。
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; // double threshold
        }
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;
        else {               // zero initial threshold signifies using defaults
            //table初始化,数组长度为16,扩容阈值16*0.75=12,初始化或直接返回
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
        if (newThr == 0) {
            float ft = (float)newCap * loadFactor;
            newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                      (int)ft : Integer.MAX_VALUE);
        }
        threshold = newThr;
        @SuppressWarnings({"rawtypes","unchecked"})
            Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
        table = newTab;
        //将数组中的所有元素重新计算hash值,放入到新数组中
        //计算元素的存储位置:(e.hash & oldCap)等价于(e.hash & (newCap - 1))
        //若(e.hash & oldCap)=0表示高位的hash值为0,此时元素还是放在原来的索引处,
        //若不为0,表示高位的hash值为1,此时元素放置的位置是(当前索引位置j+oldCap)。
        if (oldTab != null) {
            for (int j = 0; j < oldCap; ++j) {
                Node<K,V> e;
                if ((e = oldTab[j]) != null) {
                    oldTab[j] = null;
                    //索引j位置只要一个节点,将元素存放到新的数组中,然后处理下一个索引的元素
                    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
                        //链表结构元素位置调整
                        //loHead、loTail 表示当前位置j的头结点和尾结点
                        //hiHead、hiTail 表示j+oldCap处的头结点和尾结点
                        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) {
                                //元素还是放在原来的位置j处,尾插法,即保持原来的顺序
                                if (loTail == null)
                                    loHead = e;
                                else
                                    loTail.next = e;
                                loTail = e;
                            }
                            else {
                                //元素还是放在原来的位置j+oldCap处
                                if (hiTail == null)
                                    hiHead = e;
                                else
                                    hiTail.next = e;
                                hiTail = e;
                            }
                        } while ((e = next) != null);
                        //调整j处、j+oldCap处的newTab引用
                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead;
                        }
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }

1.新增节点后,size值大于扩容阈值threshold,扩容。

2.数组大小和扩容阈值变为原来的两倍newCap = 2*oldCap。

3. 链表结构扩容,(e.hash & oldCap) == 0则节点在桶中的索引位置不变,若不为0则索引位置为(index+oldCap)。当(e.hash & oldCap) == 0时,e.hash & (oldCap -1)等价于e.hash & (newCap -1)。

4.对于树形结构扩容,扩容后节点数小于等于6则红黑树转链表,否则继续树化(链表转红黑树)。

8.链表转红黑树过程

    final void treeifyBin(Node<K,V>[] tab, int hash) {
        int n, index; Node<K,V> e;
        //当table长度小于最小树化容量64时,虽然链表的长度达到了8个,此时进行
        //扩容,而不是进行树化
        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;
            //遍历链表节点,将链表节点转成树节点,链表的顺序保持不变,且增加prev引用
            //变得好像“双向链表”
            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);
        }
    }
        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 {
                    //从插入的第二个节点开始
                    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)
                            dir = -1;
                        else if (ph < h)
                            dir = 1;
                        else if ((kc == null &&
                                  (kc = comparableClassFor(k)) == null) ||
                                 (dir = compareComparables(kc, k, pk)) == 0)
                            //当两个节点的hash值相等时,根据某一个规定的排序规则排序
                            dir = tieBreakOrder(k, pk);

                        //xp为插入节点x的父节点
                        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);
        }
        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;
                //first是节点未树化前链表中的第一个元素
                TreeNode<K,V> first = (TreeNode<K,V>)tab[index];
                if (root != first) {
                    //root根节点不是桶中的第一个元素
                    //设置为第一个元素
                    Node<K,V> rn;
                    tab[index] = root;

                    //将root从原来的链表位置中移除,添加到first节点前,成为第一个节点。
                    //原来:first ... rp root rn
                    //变更后:root first ... rp rn
                    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);
            }
        }

Node->TreeNode

转化为红黑树后根节点为桶中的第一个节点,根结点也是链表中的第一个结点。

1.扩容条件:增加节点后指定索引处链表长度达到阈值8;table数组的长度达到64。

2.将桶中指定索引位置的单链表转换为双链表,链表中元素位置不变,增加prev引用。

3.节点插入顺序是节点在链表中的顺序,根据节点的hash值大小转化为红黑树。将红黑树根节点置为桶中的第一个节点。

4.校验红黑树是否符合规范。

9.红黑树转链表过程

        //红黑树转链表       
        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;
        }

TreeNode->Node

1.树节点长度小于等于6时进行非树化。

2.树节点转为链表节点,单链表,采用尾插法。

10.遍历

遍历的流程可以参考TreeMap源码解析。

        //找到第一个节点,数组从小到大第一个不为null的节点。        
        HashIterator() {
            expectedModCount = modCount;
            Node<K,V>[] t = table;
            current = next = null;
            index = 0;
            if (t != null && size > 0) { // advance to first entry
                do {} while (index < t.length && (next = t[index++]) == null);
            }
        }

        final Node<K,V> nextNode() {
            Node<K,V>[] t;
            //要输出的节点
            Node<K,V> e = next;
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            if (e == null)
                throw new NoSuchElementException();
            //通过next找到下一个要输出的节点(顺序是链表的顺序)
            //如果当前索引位置的元素全部遍历完成,则查看数组的下一个索引。
            if ((next = (current = e).next) == null && (t = table) != null) {
                do {} while (index < t.length && (next = t[index++]) == null);
            }
            return e;
        }

1.找到第一个Node节点,索引从小到大第一个table[index]不为null的节点。

2.设当前节点为e,下一个节点为next。若table[index]链表结构或树结构的节点数超过一个,则使用e.next继续查找下一个节点。直到e.next==null,查找table[index+1]处不为空的节点。

3.打印当前节点e。

11.常见问题

关于HashMap节点的属性说明:key,value,hash,next,prev,parent,left,right,red

TreeNode继承了Node,prev,next用于链表;parent,left,right,red用于红黑树;方便与链表和红黑树的相互转换。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值