简单读HashMap源码笔记

package java.util;

import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import sun.misc.SharedSecrets;
/**
 * @author txw
 * @date 2020/1/12
 * HashMap功能和Hashtable大致相同,不过它是非同步的,并且允许Null值
 * HashMap不能保证map的顺序
 * 如果迭代非常重要,不要设置太高的初始容量
 * HashMap有两个参数影响它的性能:出事容量,负荷系数
 * 当HashMao的entry数目超过负荷数量时,HashMap进行重新hash,并且容量增加到2倍
 * 负荷系数越高空间消耗越少但是查找时间增加
 * 快速失败机制:如果在iterator创建之后,map有任何结构上的变化(除了迭代器的remove),迭代器将抛出并发修改异常
 * 不能保证肯定抛出并发修改异常,不能通过依赖这个异常来编写程序
 */
public class HashMap<K,V> extends AbstractMap<K,V>
        implements Map<K,V>, Cloneable, Serializable {

    private static final long serialVersionUID = 362498820763181265L;

    // 初始容器容量16
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

    // 如果初始化容量大于该数,则替换为该数。主要目的是初始化2的k次方的容器
    static final int MAXIMUM_CAPACITY = 1 << 30;

    // 负荷系数
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

    // 当一个桶里元素数量超过8个,使用树
    static final int TREEIFY_THRESHOLD = 8;

    // 当一个桶里的元素数目少于这个数值时使用链表
    static final int UNTREEIFY_THRESHOLD = 6;

    // 对容器进行树化的最小容量。为了避免在哈希表建立初期,多个键值对恰好被放入了同一个链表中而导致不必要的转化。
    static final int MIN_TREEIFY_CAPACITY = 64;

    // map中的基本单位
    static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        V value;
        Node<K,V> next;

        Node(int hash, K key, V value, Node<K,V> next) {
            this.hash = hash;
            this.key = key;
            this.value = value;
            this.next = next;
        }

        public final K getKey()        { return key; }
        public final V getValue()      { return value; }
        public final String toString() { return key + "=" + value; }

        public final int hashCode() {
            return Objects.hashCode(key) ^ Objects.hashCode(value);
        }

        public final V setValue(V newValue) {
            V oldValue = value;
            value = newValue;
            return oldValue;
        }

        public final boolean equals(Object o) {
            if (o == this)
                return true;
            if (o instanceof Map.Entry) {
                Map.Entry<?,?> e = (Map.Entry<?,?>)o;
                if (Objects.equals(key, e.getKey()) &&
                        Objects.equals(value, e.getValue()))
                    return true;
            }
            return false;
        }
    }

    // 对key的hashCode进行hash
    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

    // 获取x的类型
    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;
    }

    // 比较
    @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));
    }

    // 计算传入参数最接近的2次方数
    static final int tableSizeFor(int cap) {
        int n = cap - 1;
        n |= n >>> 1;
        n |= n >>> 2;
        n |= n >>> 4;
        n |= n >>> 8;
        n |= n >>> 16;
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
    }

    // 表
    transient Node<K,V>[] table;

    // TODO
    transient Set<Map.Entry<K,V>> entrySet;

    // 元素数量
    transient int size;

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

    // hashtable重新调整大小的阀值
    int threshold;

    // hashtable的负荷系数
    final float loadFactor;

    // 传入初始化容量和复合系数构建hashmap对象
    // 如果传入的容量不为2的次方,将初始化比传入值大的最接近的2次方的容量
    // HashMap寻找Index位置是通过位运算计算出来的,但是原理是对length取余数,只有是2的次幂的时候h & (length - 1) == h % length
    // 因此通过2次方,能够在hash时获取更快的运算速度
    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;
        this.threshold = tableSizeFor(initialCapacity);
    }

    // 初始化
    public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }

    // 默认容量初始化
    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }

    // 通过Map初始化
    public HashMap(Map<? extends K, ? extends V> m) {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        putMapEntries(m, false);
    }

    // 写入Map
    // m->其他map对象
    // evict->如果为false说明表是创建模式
    final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
        // 获取参数map大小
        int s = m.size();
        if (s > 0) {
            // 判断是否已经初始化table
            if (table == null) {
                // 获取初始化大小,计算所需桶数目
                float ft = ((float)s / loadFactor) + 1.0F;
                int t = ((ft < (float)MAXIMUM_CAPACITY) ?
                        (int)ft : MAXIMUM_CAPACITY);
                // 将所需初始化的大小存放在threshold中
                if (t > threshold)
                    threshold = tableSizeFor(t);
            }

            // 表存在,并且插入的map大小大于阀值,进行resize
            else if (s > threshold)
                resize();

            // 写入m中数据
            for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
                K key = e.getKey();
                V value = e.getValue();
                putVal(hash(key), key, value, false, evict);
            }
        }
    }

    // 返回元素(映射)数目
    public int size() {
        return size;
    }

    // 判断表是否为空
    public boolean isEmpty() {
        return size == 0;
    }

    // 取值,key可为null
    public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }

    // 从表中查询对应hash和key的Node
    final Node<K,V> getNode(int hash, Object key) {
        Node<K,V>[] tab; // 表
        Node<K,V> first, e; // first-对应桶中第一个元素
        int n; // n-表容量
        K k;
        if ((tab = table) != null && (n = tab.length) > 0 &&
                (first = tab[(n - 1) & hash]) != null) {
            // 取对应桶中第一个元素
            if (first.hash == hash && // always check first node
                    ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
            // 取first中后续元素校验
            if ((e = first.next) != null) {
                // 如果为红黑树,走红黑树get方法
                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);
            }
        }
        return null;
    }

    // 通过是否有Node判断包含key
    public boolean containsKey(Object key) {
        return getNode(hash(key), key) != null;
    }

    // 写入值,key相同则value替换
    // key可以为null
    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

    /**
     * @param hash hash for key
     * @param key the key
     * @param value the value to put
     * @param onlyIfAbsent if true, don't change existing value 如果为true,不改变已存在的值
     * @param evict if false, the table is in creation mode. 如果为false,说明表在创建
     * @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; // 表中i桶中的元素
        int n, i; // n表长度; i为表中定位位置
        if ((tab = table) == null || (n = tab.length) == 0)
            // 如果表为空表,进行resize()初始化
            n = (tab = resize()).length;
        // 初始化后写值
        if ((p = tab[i = (n - 1) & hash]) == null)
            // 当前桶为空,直接写值
            tab[i] = newNode(hash, key, value, null);
        else {
            // hash冲突
            Node<K,V> e; // 当前位置旧值
            K k;
            // key相同,值替换
            if (p.hash == hash &&
                    ((k = p.key) == key || (key != null && key.equals(k))))
                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) {
                        p.next = newNode(hash, key, value, null);
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            // 如果长度大于等于8个,树化
                            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;
                // 如果原node为空或onlyIfAbsent为false则修改
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                // 空方法,可通过继承增强,LinkedHashMap回调
                afterNodeAccess(e);
                return oldValue;
            }
        }
        // 增加修改次数
        ++modCount;
        // 元素数目大于了阀值,2扩增
        if (++size > threshold)
            resize();
        // 空方法,可通过继承增强,LinkedHashMap回调
        afterNodeInsertion(evict);
        return null;
    }

    // 初始化或者2倍表容量
    // 如果表为空,根据threshold进行初始化
    // 如果不为空,涉及到表内元素的移动
    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) {
            // 如果旧表容量大于默认最大容量,将阀值设为Integer.MAX
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            // 否则,获取*2的表大小和阀值
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                    oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; // double threshold
        }

        // 如果表为空阀值不为空,新表容量等于阀值
        else if (oldThr > 0)
            newCap = oldThr;

            // 表为空阀值为空,设置默认表容量和阀值
        else {
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
        // 如果新表阀值为0,进行设置
        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;

        // 旧表数据迁移新表
        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;
    }

    // 替换桶中Node的索引方式,如果表太小,通过resize替代
    final void treeifyBin(Node<K,V>[] tab, int hash) {
        int n, index;// n- 表容量; index:桶位置
        Node<K,V> e; // 对应桶的第一个元素

        // 表中元素少于最小树化数量,进行resize
        if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
            resize();

        else if ((e = tab[index = (n - 1) & hash]) != null) {
            TreeNode<K,V> hd = null,  // hd: 树化后桶连接元素
                    tl = null; // 临时temp

            do {
                // 生成TreeNode
                TreeNode<K,V> p = replacementTreeNode(e, null);
                // 将链表转化为treeNodes链表
                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);
        }
    }

    // 将map写入当前对象
    public void putAll(Map<? extends K, ? extends V> m) {
        putMapEntries(m, true);
    }

    // 移除Key对应的Node,返回value
    public V remove(Object key) {
        Node<K,V> e;
        return (e = removeNode(hash(key), key, null, false, true)) == null ?
                null : e.value;
    }

    /**
     * @param matchValue 如果为true,则在值相等时移除
     * @param movable true,删除时移动其他节点,如果为false,在删除时不移动其他节点
     */
    final Node<K,V> removeNode(int hash, Object key, Object value,
                               boolean matchValue, boolean movable) {
        Node<K,V>[] tab; // 表
        Node<K,V> p; // 桶中第一个元素或被删除的前一个元素
        int n, index; // n - 表容量;index桶位置
        // 表不为空并且hash对应桶位置有值
        if ((tab = table) != null && (n = tab.length) > 0 &&
                (p = tab[index = (n - 1) & hash]) != null) {
            Node<K,V> node = null, e; // node-被删除元素, e- 临时Node
            K k; // 临时key
            V v; // 临时value

            // 校验对应桶中第一个Node
            if (p.hash == hash &&
                    ((k = p.key) == key || (key != null && key.equals(k))))
                node = p;
            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);
                }
            }

            // 只有在matchVlue为false或者为true并且值相等的时候进行删除
            if (node != null && (!matchValue || (v = node.value) == value ||
                    (value != null && value.equals(v)))) {
                // 红黑树删除
                if (node instanceof TreeNode)
                    ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);

                    // 桶内第一个元素删除
                else if (node == p)
                    tab[index] = node.next;

                    // 链表删除
                else
                    p.next = node.next;

                // 增加修改次数
                ++modCount;
                // 元素数目-1
                --size;
                // 空方法,可通过继承扩展,LinkedHashMap回调
                afterNodeRemoval(node);
                return node;
            }
        }
        return null;
    }

    // 移除map中所有的映射(表容量未变)
    public void clear() {
        Node<K,V>[] tab;
        modCount++;
        if ((tab = table) != null && size > 0) {
            size = 0;
            for (int i = 0; i < tab.length; ++i)
                tab[i] = null;
        }
    }

    // 如果map中包含value返回ture
    public boolean containsValue(Object value) {
        Node<K,V>[] tab; V v;
        if ((tab = table) != null && size > 0) {
            for (int i = 0; i < tab.length; ++i) {
                for (Node<K,V> e = tab[i]; e != null; e = e.next) {
                    if ((v = e.value) == value ||
                            (value != null && value.equals(v)))
                        return true;
                }
            }
        }
        return false;
    }

    // 初始化了KeySet,但是这个集合中并没有内容,操作都是HashMap中的操作
    public Set<K> keySet() {
        Set<K> ks = keySet;
        if (ks == null) {
            ks = new KeySet();
            keySet = ks;
        }
        return ks;
    }

    final class KeySet extends AbstractSet<K> {

        public final int size()                 { return size; }

        public final void clear()               { HashMap.this.clear(); }

        public final Iterator<K> iterator()     { return new KeyIterator(); }

        public final boolean contains(Object o) { return containsKey(o); }

        public final boolean remove(Object key) {
            return removeNode(hash(key), key, null, false, true) != null;
        }

        // 可分割迭代器
        public final Spliterator<K> spliterator() {
            return new KeySpliterator<>(HashMap.this, 0, -1, 0, 0);
        }

        // 可能会抛出并发修改异常
        public final void forEach(Consumer<? super K> action) {
            Node<K,V>[] tab;
            if (action == null)
                throw new NullPointerException();
            if (size > 0 && (tab = table) != null) {
                int mc = modCount;
                for (int i = 0; i < tab.length; ++i) {
                    for (Node<K,V> e = tab[i]; e != null; e = e.next)
                        action.accept(e.key);
                }
                if (modCount != mc)
                    throw new ConcurrentModificationException();
            }
        }
    }

    // 初始化了value的集合,集合为空
    public Collection<V> values() {
        Collection<V> vs = values;
        if (vs == null) {
            vs = new Values();
            values = vs;
        }
        return vs;
    }


    final class Values extends AbstractCollection<V> {

        public final int size()                 { return size; }

        public final void clear()               { HashMap.this.clear(); }

        public final Iterator<V> iterator()     { return new ValueIterator(); }

        public final boolean contains(Object o) { return containsValue(o); }

        // 可分割迭代器
        public final Spliterator<V> spliterator() {
            return new ValueSpliterator<>(HashMap.this, 0, -1, 0, 0);
        }

        // 可能会抛出并发修改异常
        public final void forEach(Consumer<? super V> action) {
            Node<K,V>[] tab;
            if (action == null)
                throw new NullPointerException();
            if (size > 0 && (tab = table) != null) {
                int mc = modCount;
                for (int i = 0; i < tab.length; ++i) {
                    for (Node<K,V> e = tab[i]; e != null; e = e.next)
                        action.accept(e.value);
                }
                if (modCount != mc)
                    throw new ConcurrentModificationException();
            }
        }
    }

    // 初始化了Entry的集合,集合为空
    public Set<Map.Entry<K,V>> entrySet() {
        Set<Map.Entry<K,V>> es;
        return (es = entrySet) == null ? (entrySet = new EntrySet()) : es;
    }

    final class EntrySet extends AbstractSet<Map.Entry<K,V>> {
        public final int size()                 { return size; }
        public final void clear()               { HashMap.this.clear(); }
        public final Iterator<Map.Entry<K,V>> iterator() {
            return new EntryIterator();
        }
        public final boolean contains(Object o) {
            if (!(o instanceof Map.Entry))
                return false;
            Map.Entry<?,?> e = (Map.Entry<?,?>) o;
            Object key = e.getKey();
            Node<K,V> candidate = getNode(hash(key), key);
            return candidate != null && candidate.equals(e);
        }
        public final boolean remove(Object o) {
            if (o instanceof Map.Entry) {
                Map.Entry<?,?> e = (Map.Entry<?,?>) o;
                Object key = e.getKey();
                Object value = e.getValue();
                return removeNode(hash(key), key, value, true, true) != null;
            }
            return false;
        }

        // 可分割迭代器
        public final Spliterator<Map.Entry<K,V>> spliterator() {
            return new EntrySpliterator<>(HashMap.this, 0, -1, 0, 0);
        }

        // 可能会抛出并发修改异常
        public final void forEach(Consumer<? super Map.Entry<K,V>> action) {
            Node<K,V>[] tab;
            if (action == null)
                throw new NullPointerException();
            if (size > 0 && (tab = table) != null) {
                int mc = modCount;
                for (int i = 0; i < tab.length; ++i) {
                    for (Node<K,V> e = tab[i]; e != null; e = e.next)
                        action.accept(e);
                }
                if (modCount != mc)
                    throw new ConcurrentModificationException();
            }
        }
    }

    // jdk8新增方法
    @Override
    public V getOrDefault(Object key, V defaultValue) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? defaultValue : e.value;
    }

    // 如果有值,不写入
    @Override
    public V putIfAbsent(K key, V value) {
        return putVal(hash(key), key, value, true, true);
    }

    // 从map中移除key和value相等的映射
    @Override
    public boolean remove(Object key, Object value) {
        return removeNode(hash(key), key, value, true, true) != null;
    }

    // 从map中寻找key和value对应的映射替换value
    @Override
    public boolean replace(K key, V oldValue, V newValue) {
        Node<K,V> e; V v;
        if ((e = getNode(hash(key), key)) != null &&
                ((v = e.value) == oldValue || (v != null && v.equals(oldValue)))) {
            e.value = newValue;
            afterNodeAccess(e);
            return true;
        }
        return false;
    }

    // 从map中寻找key相同的映射替换value
    @Override
    public V replace(K key, V value) {
        Node<K,V> e;
        if ((e = getNode(hash(key), key)) != null) {
            V oldValue = e.value;
            e.value = value;
            afterNodeAccess(e);
            return oldValue;
        }
        return null;
    }


    // 如果表中不存在key对应的映射或者对应映射的value不为null,执行函数
    // 将函数值加入映射
    // 如果存在对应的映射,返回对应的value
    @Override
    public V computeIfAbsent(K key,
                             Function<? super K, ? extends V> mappingFunction) {
        if (mappingFunction == null)
            throw new NullPointerException();
        int hash = hash(key); // key对应的hash
        Node<K,V>[] tab; // 表
        Node<K,V> first; // 桶中第一个元素
        int n, i; // n -> 表长度, i->桶位置
        int binCount = 0; // 桶中元素数目
        TreeNode<K,V> t = null; // 桶中树节点的根节点
        Node<K,V> old = null; // key对应的Node

        // 当表元素数目超过阀值||表未初始化, 需要对表进行resize
        if (size > threshold || (tab = table) == null ||
                (n = tab.length) == 0)
            n = (tab = resize()).length;

        // 获取hash对应桶中第一个元素
        if ((first = tab[i = (n - 1) & hash]) != null) {
            // 从树中获取对应Node
            if (first instanceof TreeNode)
                old = (t = (TreeNode<K,V>)first).getTreeNode(hash, key);

                // 从链表中获取对应Node
            else {
                Node<K,V> e = first; K k;
                do {
                    if (e.hash == hash &&
                            ((k = e.key) == key || (key != null && key.equals(k)))) {
                        old = e;
                        break;
                    }
                    ++binCount;
                } while ((e = e.next) != null);
            }

            // 获取对应Node的旧值
            V oldValue;
            if (old != null && (oldValue = old.value) != null) {
                afterNodeAccess(old);
                return oldValue;
            }
        }

        // 执行函数
        V v = mappingFunction.apply(key);

        // 执行结果不为空,返回执行结果
        if (v == null) {
            return null;
        }
        // 如果原节点对应value为null,返回对应节点执行函数后的value
        else if (old != null) {
            old.value = v;
            afterNodeAccess(old);
            return v;
        }

        // 如果桶是红黑树,写入树节点
        else if (t != null)
            t.putTreeVal(this, tab, hash, key, v);

            // 写入链表节点
        else {
            tab[i] = newNode(hash, key, v, first);

            // 如果查过树化阀值,进行树化
            if (binCount >= TREEIFY_THRESHOLD - 1)
                treeifyBin(tab, hash);
        }
        // 增加修改次数
        ++modCount;
        // 增加元素计数
        ++size;
        afterNodeInsertion(true);
        return v;
    }

    // 如果Key对应的映射存在,执行函数方法,如果函数结果为null,则删除该节点
    public V computeIfPresent(K key,
                              BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
        if (remappingFunction == null)
            throw new NullPointerException();
        Node<K,V> e; V oldValue;
        int hash = hash(key);
        if ((e = getNode(hash, key)) != null &&
                (oldValue = e.value) != null) {
            V v = remappingFunction.apply(key, oldValue);
            if (v != null) {
                e.value = v;
                afterNodeAccess(e);
                return v;
            }
            else
                removeNode(hash, key, null, false, true);
        }
        return null;
    }

    // 对key对应Node执行函数,如果节点不存在,插入;节点存在,值替换,返回计算后值
    @Override
    public V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
        if (remappingFunction == null)
            throw new NullPointerException();

        int hash = hash(key); // key对应的hash
        Node<K,V>[] tab; // 表
        Node<K,V> first; // 桶中第一个元素
        int n, i; // n -> 表长度, i->桶位置
        int binCount = 0; // 桶中元素数目
        TreeNode<K,V> t = null; // 桶中树节点的根节点
        Node<K,V> old = null; // key对应的Node

        // 当表元素数目超过阀值||表未初始化, 需要对表进行resize
        if (size > threshold || (tab = table) == null ||
                (n = tab.length) == 0)
            n = (tab = resize()).length;

        // 获取hash对应桶中第一个元素
        if ((first = tab[i = (n - 1) & hash]) != null) {
            // 从树中获取对应节点
            if (first instanceof TreeNode)
                old = (t = (TreeNode<K,V>)first).getTreeNode(hash, key);

                // 从桶中获取对应节点
            else {
                Node<K,V> e = first; K k;
                do {
                    if (e.hash == hash &&
                            ((k = e.key) == key || (key != null && key.equals(k)))) {
                        old = e;
                        break;
                    }
                    ++binCount;
                } while ((e = e.next) != null);
            }
        }


        V oldValue = (old == null) ? null : old.value;
        V v = remappingFunction.apply(key, oldValue);

        // 节点不为空
        if (old != null) {
            // 计算值不为空
            if (v != null) {
                // 值替换
                old.value = v;
                afterNodeAccess(old);
            }

            // 计算值为空,删除节点
            else
                removeNode(hash, key, null, false, true);
        }

        // 节点为空,函数值不为空
        else if (v != null) {

            // 有根节点,写入新节点
            if (t != null)
                t.putTreeVal(this, tab, hash, key, v);

                // 链表写入新节点
            else {
                tab[i] = newNode(hash, key, v, first);
                if (binCount >= TREEIFY_THRESHOLD - 1)
                    treeifyBin(tab, hash);
            }
            // 修改次数增加
            ++modCount;
            // 表元素数+1
            ++size;
            afterNodeInsertion(true);
        }
        return v;
    }


    @Override
    public V merge(K key, V value,
                   BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
        if (value == null)
            throw new NullPointerException();
        if (remappingFunction == null)
            throw new NullPointerException();

        int hash = hash(key); // key对应的hash
        Node<K,V>[] tab; // 表
        Node<K,V> first; // 桶中第一个元素
        int n, i; // n -> 表长度, i->桶位置
        int binCount = 0; // 桶中元素数目
        TreeNode<K,V> t = null; // 桶中树节点的根节点
        Node<K,V> old = null; // key对应的Node

        // 当表元素数目超过阀值||表未初始化, 需要对表进行resize
        if (size > threshold || (tab = table) == null ||
                (n = tab.length) == 0)
            n = (tab = resize()).length;

        // 获取hash对应桶中第一个元素
        if ((first = tab[i = (n - 1) & hash]) != null) {

            // 从树中获取对应节点
            if (first instanceof TreeNode)
                old = (t = (TreeNode<K,V>)first).getTreeNode(hash, key);

                // 从链表中获取对应节点
            else {
                Node<K,V> e = first; K k;
                do {
                    if (e.hash == hash &&
                            ((k = e.key) == key || (key != null && key.equals(k)))) {
                        old = e;
                        break;
                    }
                    ++binCount;
                } while ((e = e.next) != null);
            }
        }

        // 如果对应节点存在
        if (old != null) {
            V v;
            // 对value执行合并方法
            if (old.value != null)
                v = remappingFunction.apply(old.value, value);
            else
                v = value;

            // 如果执行结果不为空,写入;为空,删除节点
            if (v != null) {
                old.value = v;
                afterNodeAccess(old);
            }
            else
                removeNode(hash, key, null, false, true);
            return v;
        }

        // 节点不存在
        if (value != null) {
            // 树根节点存在,写入新节点
            if (t != null)
                t.putTreeVal(this, tab, hash, key, value);

                // 写入链表节点
            else {
                tab[i] = newNode(hash, key, value, first);
                if (binCount >= TREEIFY_THRESHOLD - 1)
                    treeifyBin(tab, hash);
            }

            // 增加修改次数
            ++modCount;
            // 增加元素数
            ++size;
            afterNodeInsertion(true);
        }
        return value;
    }

    // 接收Lambda表达式的foreach方法
    @Override
    public void forEach(BiConsumer<? super K, ? super V> action) {
        Node<K,V>[] tab;
        if (action == null)
            throw new NullPointerException();
        if (size > 0 && (tab = table) != null) {
            int mc = modCount;
            for (int i = 0; i < tab.length; ++i) {
                for (Node<K,V> e = tab[i]; e != null; e = e.next)
                    action.accept(e.key, e.value);
            }
            if (modCount != mc)
                throw new ConcurrentModificationException();
        }
    }

    // 对map中所有节点执行函数,计算结果替换value
    @Override
    public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
        Node<K,V>[] tab;
        if (function == null)
            throw new NullPointerException();
        if (size > 0 && (tab = table) != null) {
            int mc = modCount;
            for (int i = 0; i < tab.length; ++i) {
                for (Node<K,V> e = tab[i]; e != null; e = e.next) {
                    e.value = function.apply(e.key, e.value);
                }
            }
            if (modCount != mc)
                throw new ConcurrentModificationException();
        }
    }

    // 浅克隆,key和value没有复制
    @SuppressWarnings("unchecked")
    @Override
    public Object clone() {
        HashMap<K,V> result;
        try {
            result = (HashMap<K,V>)super.clone();
        } catch (CloneNotSupportedException e) {
            throw new InternalError(e);
        }
        result.reinitialize();
        result.putMapEntries(this, false);
        return result;
    }

    // 序列化时使用到的方法
    final float loadFactor() { return loadFactor; }
    final int capacity() {
        return (table != null) ? table.length :
                (threshold > 0) ? threshold :
                        DEFAULT_INITIAL_CAPACITY;
    }

    // 序列化到流
    private void writeObject(java.io.ObjectOutputStream s)
            throws IOException {
        int buckets = capacity();
        // Write out the threshold, loadfactor, and any hidden stuff
        s.defaultWriteObject();
        s.writeInt(buckets);
        s.writeInt(size);
        internalWriteEntries(s);
    }

    // 从输入流读取HashMap
    private void readObject(java.io.ObjectInputStream s)
            throws IOException, ClassNotFoundException {
        // Read in the threshold (ignored), loadfactor, and any hidden stuff
        s.defaultReadObject();
        reinitialize();
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new InvalidObjectException("Illegal load factor: " +
                    loadFactor);
        // 读取并忽略桶数量
        s.readInt();
        // 读取元素数
        int mappings = s.readInt();
        if (mappings < 0)
            throw new InvalidObjectException("Illegal mappings count: " +
                    mappings);
            // 读取元素写入桶中
        else if (mappings > 0) { // (if zero, use defaults)
            // Size the table using given load factor only if within
            // range of 0.25...4.0
            // 取默认负荷系数
            float lf = Math.min(Math.max(0.25f, loadFactor), 4.0f);
            // 需要的桶数目
            float fc = (float)mappings / lf + 1.0f;

            // 设置的桶数目
            int cap = ((fc < DEFAULT_INITIAL_CAPACITY) ?
                    DEFAULT_INITIAL_CAPACITY :
                    (fc >= MAXIMUM_CAPACITY) ?
                            MAXIMUM_CAPACITY :
                            tableSizeFor((int)fc));
            // 阀值
            float ft = (float)cap * lf;
            threshold = ((cap < MAXIMUM_CAPACITY && ft < MAXIMUM_CAPACITY) ?
                    (int)ft : Integer.MAX_VALUE);

            // Check Map.Entry[].class since it's the nearest public type to
            // what we're actually creating.
            SharedSecrets.getJavaOISAccess().checkArray(s, Map.Entry[].class, cap);
            @SuppressWarnings({"rawtypes","unchecked"})
            Node<K,V>[] tab = (Node<K,V>[])new Node[cap];
            table = tab;

            // 读写key value
            for (int i = 0; i < mappings; i++) {
                @SuppressWarnings("unchecked")
                K key = (K) s.readObject();
                @SuppressWarnings("unchecked")
                V value = (V) s.readObject();
                putVal(hash(key), key, value, false, false);
            }
        }
    }

    // HashMap迭代器的抽象父类,定义并实现了部分方法
    abstract class HashIterator {
        Node<K,V> next;        // 下一个entry对象
        Node<K,V> current;     // 当前entry对象
        int expectedModCount;  // 记录修改次数
        int index;             // 当前桶位置

        HashIterator() {
            expectedModCount = modCount;
            Node<K,V>[] t = table; // 当前表
            current = next = null;
            index = 0;

            // 赋值,寻找第一个桶中有元素的作为index
            if (t != null && size > 0) { // advance to first entry
                do {} while (index < t.length && (next = t[index++]) == null);
            }
        }

        // 判断是否有下个元素
        public final boolean hasNext() {
            return next != 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;
        }

        // 移除当前元素
        public final void remove() {
            Node<K,V> p = current;
            if (p == null)
                throw new IllegalStateException();
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            current = null;
            K key = p.key;
            removeNode(hash(key), key, null, false, false);
            expectedModCount = modCount;
        }
    }

    // key迭代器
    final class KeyIterator extends HashIterator
            implements Iterator<K> {
        public final K next() { return nextNode().key; }
    }

    // value迭代器
    final class ValueIterator extends HashIterator
            implements Iterator<V> {
        public final V next() { return nextNode().value; }
    }

    // entry迭代器
    final class EntryIterator extends HashIterator
            implements Iterator<Map.Entry<K,V>> {
        public final Map.Entry<K,V> next() { return nextNode(); }
    }

    /* ------------------------------------------------------------ */
    // 可分割HashMap
    static class HashMapSpliterator<K,V> {
        final HashMap<K,V> map;  // 当前hashmap
        Node<K,V> current;          // 当前节点
        int index;                  // 迭代器开始遍历的桶节点Index
        int fence;                  // 迭代器遍历的桶节点上限index
        int est;                    // 需要遍历的元素个数
        int expectedModCount;       // 期望操作数,用于并发修改异常

        // 初始化可分割HashMap
        HashMapSpliterator(HashMap<K,V> m, int origin,
                           int fence, int est,
                           int expectedModCount) {
            this.map = m;
            this.index = origin;
            this.fence = fence;
            this.est = est;
            this.expectedModCount = expectedModCount;
        }

        // 第一次使用时初始化上限和元素个数
        // 返回桶个数
        final int getFence() {
            int hi;
            if ((hi = fence) < 0) {
                HashMap<K,V> m = map;
                est = m.size;
                expectedModCount = m.modCount;
                Node<K,V>[] tab = m.table;
                hi = fence = (tab == null) ? 0 : tab.length;
            }
            return hi;
        }

        // 获取元素个数
        public final long estimateSize() {
            getFence(); // force init
            return (long) est;
        }
    }

    // 可分割的key迭代器
    static final class KeySpliterator<K,V>
            extends HashMapSpliterator<K,V>
            implements Spliterator<K> {
        KeySpliterator(HashMap<K,V> m, int origin, int fence, int est,
                       int expectedModCount) {
            super(m, origin, fence, est, expectedModCount);
        }

        // 尝试切割, 从迭代器中取桶位置前一半切割出去
        public KeySpliterator<K,V> trySplit() {
            int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
            return (lo >= mid || current != null) ? null :
                    new KeySpliterator<>(map, lo, index = mid, est >>>= 1,
                            expectedModCount);
        }

        // 对每个元素执行函数
        public void forEachRemaining(Consumer<? super K> action) {
            int i, hi, mc; // i->,hi->桶上限位置,mc->修改次数
            if (action == null)
                throw new NullPointerException();

            HashMap<K,V> m = map; // 获取映射
            Node<K,V>[] tab = m.table;  // 获取表

            if ((hi = fence) < 0) {
                mc = expectedModCount = m.modCount;
                hi = fence = (tab == null) ? 0 : tab.length;
            }
            else
                mc = expectedModCount;
            if (tab != null && tab.length >= hi &&
                    (i = index) >= 0 && (i < (index = hi) || current != null)) {
                Node<K,V> p = current; // 遍历的当前节点
                current = null;
                do {
                    // 节点为空,跳转到下个桶
                    if (p == null)
                        p = tab[i++];

                        // 节点不为空,执行函数
                    else {
                        action.accept(p.key);
                        p = p.next;
                    }
                } while (p != null || i < hi);

                // 并发修改异常
                if (m.modCount != mc)
                    throw new ConcurrentModificationException();
            }
        }

        // 如果存在其他元素,尝试对其执行函数,执行成功返回true,否则返回false
        public boolean tryAdvance(Consumer<? super K> action) {
            int hi;
            if (action == null)
                throw new NullPointerException();

            Node<K,V>[] tab = map.table; // 获取表

            if (tab != null && tab.length >= (hi = getFence()) && index >= 0) {

                while (current != null || index < hi) {
                    if (current == null)
                        current = tab[index++];
                    else {
                        K k = current.key;
                        current = current.next;
                        action.accept(k);
                        if (map.modCount != expectedModCount)
                            throw new ConcurrentModificationException();
                        return true;
                    }
                }
            }
            return false;
        }

        // 返回特征值
        public int characteristics() {
            return (fence < 0 || est == map.size ? Spliterator.SIZED : 0) |
                    Spliterator.DISTINCT;
        }
    }

    static final class ValueSpliterator<K,V>
            extends HashMapSpliterator<K,V>
            implements Spliterator<V> {

        // 构造器
        ValueSpliterator(HashMap<K,V> m, int origin, int fence, int est,
                         int expectedModCount) {
            super(m, origin, fence, est, expectedModCount);
        }

        // 尝试切割,对半切割
        public ValueSpliterator<K,V> trySplit() {
            int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
            return (lo >= mid || current != null) ? null :
                    new ValueSpliterator<>(map, lo, index = mid, est >>>= 1,
                            expectedModCount);
        }

        // 对剩余的每个值执行函数
        public void forEachRemaining(Consumer<? super V> action) {
            int i, hi, mc;
            if (action == null)
                throw new NullPointerException();
            HashMap<K,V> m = map;
            Node<K,V>[] tab = m.table;
            if ((hi = fence) < 0) {
                mc = expectedModCount = m.modCount;
                hi = fence = (tab == null) ? 0 : tab.length;
            }
            else
                mc = expectedModCount;
            if (tab != null && tab.length >= hi &&
                    (i = index) >= 0 && (i < (index = hi) || current != null)) {
                Node<K,V> p = current;
                current = null;
                do {
                    if (p == null)
                        p = tab[i++];
                    else {
                        action.accept(p.value);
                        p = p.next;
                    }
                } while (p != null || i < hi);
                if (m.modCount != mc)
                    throw new ConcurrentModificationException();
            }
        }

        // 如果有下一个元素,执行函数,执行成功返回true,否则返回false
        public boolean tryAdvance(Consumer<? super V> action) {
            int hi;
            if (action == null)
                throw new NullPointerException();
            Node<K,V>[] tab = map.table;
            if (tab != null && tab.length >= (hi = getFence()) && index >= 0) {
                while (current != null || index < hi) {
                    if (current == null)
                        current = tab[index++];
                    else {
                        V v = current.value;
                        current = current.next;
                        action.accept(v);
                        if (map.modCount != expectedModCount)
                            throw new ConcurrentModificationException();
                        return true;
                    }
                }
            }
            return false;
        }

        // 返回特征值
        public int characteristics() {
            return (fence < 0 || est == map.size ? Spliterator.SIZED : 0);
        }
    }

    // Entry可拆分迭代器
    static final class EntrySpliterator<K,V>
            extends HashMapSpliterator<K,V>
            implements Spliterator<Map.Entry<K,V>> {

        // 构造器
        EntrySpliterator(HashMap<K,V> m, int origin, int fence, int est,
                         int expectedModCount) {
            super(m, origin, fence, est, expectedModCount);
        }

        // 尝试拆分,对半切分
        public EntrySpliterator<K,V> trySplit() {
            int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
            return (lo >= mid || current != null) ? null :
                    new EntrySpliterator<>(map, lo, index = mid, est >>>= 1,
                            expectedModCount);
        }

        // 对剩余的每个元素执行函数
        public void forEachRemaining(Consumer<? super Map.Entry<K,V>> action) {
            int i, hi, mc;
            if (action == null)
                throw new NullPointerException();
            HashMap<K,V> m = map;
            Node<K,V>[] tab = m.table;
            if ((hi = fence) < 0) {
                mc = expectedModCount = m.modCount;
                hi = fence = (tab == null) ? 0 : tab.length;
            }
            else
                mc = expectedModCount;
            if (tab != null && tab.length >= hi &&
                    (i = index) >= 0 && (i < (index = hi) || current != null)) {
                Node<K,V> p = current;
                current = null;
                do {
                    if (p == null)
                        p = tab[i++];
                    else {
                        action.accept(p);
                        p = p.next;
                    }
                } while (p != null || i < hi);
                if (m.modCount != mc)
                    throw new ConcurrentModificationException();
            }
        }

        // 如果有下一个元素,执行函数,执行成功返回true,否则返回false
        public boolean tryAdvance(Consumer<? super Map.Entry<K,V>> action) {
            int hi;
            if (action == null)
                throw new NullPointerException();
            Node<K,V>[] tab = map.table;
            if (tab != null && tab.length >= (hi = getFence()) && index >= 0) {
                while (current != null || index < hi) {
                    if (current == null)
                        current = tab[index++];
                    else {
                        Node<K,V> e = current;
                        current = current.next;
                        action.accept(e);
                        if (map.modCount != expectedModCount)
                            throw new ConcurrentModificationException();
                        return true;
                    }
                }
            }
            return false;
        }

        // 返回特征值
        public int characteristics() {
            return (fence < 0 || est == map.size ? Spliterator.SIZED : 0) |
                    Spliterator.DISTINCT;
        }
    }

    /* ------------------------------------------------------------ */
    // LinkedHashMap support


    /*
     * The following package-protected methods are designed to be
     * overridden by LinkedHashMap, but not by any other subclass.
     * Nearly all other internal methods are also package-protected
     * but are declared final, so can be used by LinkedHashMap, view
     * classes, and HashSet.
     */

    // 生成一个普通节点
    Node<K,V> newNode(int hash, K key, V value, Node<K,V> next) {
        return new Node<>(hash, key, value, next);
    }

    // 生成一个普通节点
    Node<K,V> replacementNode(Node<K,V> p, Node<K,V> next) {
        return new Node<>(p.hash, p.key, p.value, next);
    }

    // 生成一个树节点
    TreeNode<K,V> newTreeNode(int hash, K key, V value, Node<K,V> next) {
        return new TreeNode<>(hash, key, value, next);
    }

    // 将Node转为TreeNode
    TreeNode<K,V> replacementTreeNode(Node<K,V> p, Node<K,V> next) {
        return new TreeNode<>(p.hash, p.key, p.value, next);
    }

    // 重新初始化
    void reinitialize() {
        table = null;
        entrySet = null;
        keySet = null;
        values = null;
        modCount = 0;
        threshold = 0;
        size = 0;
    }

    // 回调函数,可由继承类扩展
    void afterNodeAccess(Node<K,V> p) { }
    void afterNodeInsertion(boolean evict) { }
    void afterNodeRemoval(Node<K,V> p) { }

    // 按照key-value顺序写入流
    void internalWriteEntries(java.io.ObjectOutputStream s) throws IOException {
        Node<K,V>[] tab;
        if (size > 0 && (tab = table) != null) {
            for (int i = 0; i < tab.length; ++i) {
                for (Node<K,V> e = tab[i]; e != null; e = e.next) {
                    s.writeObject(e.key);
                    s.writeObject(e.value);
                }
            }
        }
    }

    // 红黑树
    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;
        TreeNode(int hash, K key, V val, Node<K,V> next) {
            super(hash, key, val, next);
        }

        // 寻找根节点
        final TreeNode<K,V> root() {
            for (TreeNode<K,V> r = this, p;;) {
                if ((p = r.parent) == null)
                    return r;
                r = p;
            }
        }


        /**
         * 设置给定的树根节点是桶中的第一个元素
         * @param tab hash表
         * @param 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;
                // 获取当前桶中的第一个元素
                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);
            }
        }

        // 从根节点开始,根据hash和key寻找对应的树节点
        // h 查询key的hash
        // k 查询的key
        final TreeNode<K,V> find(int h, Object k, Class<?> kc) {
            TreeNode<K,V> p = this; // 当前节点
            do {
                int ph, dir; // ph->当前节点hash,dir->比较结果
                K pk; // 当前节点key
                TreeNode<K,V> pl = p.left, // 左节点
                        pr = p.right, // 右节点
                        q;
                // 当前节点hash大于查询 key
                if ((ph = p.hash) > h)
                    p = pl;
                // 当前节点hash小于查询key
                else if (ph < h)
                    p = pr;
                // 当前节点key为查询key
                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;
                // hash相同且左右不为空 ,如果实现了Comparable接口进行比较
                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;
        }

        // 从根节点或者当前节点进行查询查找节点
        final TreeNode<K,V> getTreeNode(int h, Object k) {
            return ((parent != null) ? root() : this).find(h, k, null);
        }

        // 当a.b的hash相同并且没有实现comparable接口,需要通过方法来实现排序
        static int tieBreakOrder(Object a, Object b) {
            int d;
            if (a == null || b == null ||
                    (d = a.getClass().getName().
                            compareTo(b.getClass().getName())) == 0)
                d = (System.identityHashCode(a) <= System.identityHashCode(b) ?
                        -1 : 1);
            return d;
        }

        // 从该节点形成红黑树
        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; // 设置根节点父节点为null
                    x.red = false; // 设置根节点颜色为黑色
                    root = x; // 根节点赋值
                }

                // 生成其他节点
                else {
                    K k = x.key; // 获取插入节点key
                    int h = x.hash; // 获取当前插入节点的hash
                    Class<?> kc = null; // key的class类型
                    // 从根节点开始进行比较,寻找插入节点
                    for (TreeNode<K,V> p = root;;) {
                        int dir, ph; // dir - 循环节点的hash是否大于当前节点的hash 大于则为-1,小于为1 ; ph - 循环树节点的hash

                        K pk = p.key; // 该被循环的树中当前节点的key

                        // 树中节点hash大于插入节点hash,左倾
                        if ((ph = p.hash) > h)
                            dir = -1;
                        // 树中节点hash小于插入节点hash,右倾
                        else if (ph < h)
                            dir = 1;
                        // 当前节点hash与循环节点hash相同,且没实现Comparable或者类一致,通过本地方法实现排序
                        else if ((kc == null &&
                                (kc = comparableClassFor(k)) == null) ||
                                (dir = compareComparables(kc, k, pk)) == 0)
                            dir = tieBreakOrder(k, pk);

                        // 根据dir写入当前节点或者进行下一次循环
                        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; // 临时节点
            // q 当前节点
            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;
        }

        /**
         * 在红黑树中写入新的节点
         * @param map 红黑树所在Map对象
         * @param tab 红黑树所在表
         * @param h 当前key的hash值
         * @param k 插入节点的key
         * @param v 插入节点的value
         * @return
         */
        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; // dir->树中当前节点与插入节点的比较结果 ; ph-> 树中当前节点的hash值
                K pk; // 书中当前节点的key

                // 树中当前节点hash大于插入节点hash
                if ((ph = p.hash) > h)
                    dir = -1;
                // 树中当前节点hash小于插入节点hash
                else if (ph < h)
                    dir = 1;
                // hash值相同并且key相同,不插入
                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<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);
                }

                TreeNode<K,V> xp = p;
                // 如果树中当前节点的左子树或右子树为空,生成树节点并插入
                if ((p = (dir <= 0) ? p.left : p.right) == null) {
                    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;
                    // 执行插入平衡算法,执行后替换根节点
                    moveRootToFront(tab, balanceInsertion(root, x));
                    return null;
                }
            }
        }

        /**
         * 从树中删除当前节点
         * 当树中节点过少时候,会替换为链表结构
         * @param map 删除节点的树所在的map
         * @param tab 删除节点的树所在的表
         * @param movable
         */
        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);  // too small
                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) // 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; // 当前节点的父节点

                // 当前节点左节点为空
                if (s == pr) { // p was s's direct parent
                    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) {  // detach
                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);
        }

        /**
         * Splits nodes in a tree bin into lower and upper tree bins,
         * or untreeifies if now too small. Called only from resize;
         * see above discussion about split bits and indices.
         *
         * @param map the map
         * @param tab the table for recording bin heads
         * @param index the index of the table being split
         * @param bit the bit of hash to split on
         */
        final void split(HashMap<K,V> map, Node<K,V>[] tab, int index, int bit) {
            TreeNode<K,V> b = this;
            // Relink into lo and hi lists, preserving order
            TreeNode<K,V> loHead = null, loTail = null;
            TreeNode<K,V> hiHead = null, hiTail = null;
            int lc = 0, hc = 0;
            for (TreeNode<K,V> e = b, next; e != null; e = next) {
                next = (TreeNode<K,V>)e.next;
                e.next = null;
                if ((e.hash & bit) == 0) {
                    if ((e.prev = loTail) == null)
                        loHead = e;
                    else
                        loTail.next = e;
                    loTail = e;
                    ++lc;
                }
                else {
                    if ((e.prev = hiTail) == null)
                        hiHead = e;
                    else
                        hiTail.next = e;
                    hiTail = e;
                    ++hc;
                }
            }

            if (loHead != null) {
                if (lc <= UNTREEIFY_THRESHOLD)
                    tab[index] = loHead.untreeify(map);
                else {
                    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);
                }
            }
        }

        // 左旋,将p旋转为其右孩子的左孩子
        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) {
                if ((rl = p.right = r.left) != null)
                    rl.parent = p;
                if ((pp = r.parent = p.parent) == null)
                    (root = r).red = false;
                else if (pp.left == p)
                    pp.left = r;
                else
                    pp.right = r;
                r.left = p;
                p.parent = r;
            }
            return root;
        }

        // 右旋,将p旋转为其左孩子的右孩子
        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)
                    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)) {
                    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);
                            }
                        }
                    }
                }
            }
        }

        // 删除后平衡算法:删除节点后,对树进行重新的结构化,保持红黑树的特性
        // 返回新的根节点
        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.red = false;
                    return x;
                }
                else if (x.red) {
                    x.red = false;
                    return root;
                }
                else if ((xpl = xp.left) == x) {
                    if ((xpr = xp.right) != null && xpr.red) {
                        xpr.red = false;
                        xp.red = true;
                        root = rotateLeft(root, xp);
                        xpr = (xp = x.parent) == null ? null : xp.right;
                    }
                    if (xpr == null)
                        x = xp;
                    else {
                        TreeNode<K,V> sl = xpr.left, sr = xpr.right;
                        if ((sr == null || !sr.red) &&
                                (sl == null || !sl.red)) {
                            xpr.red = true;
                            x = xp;
                        }
                        else {
                            if (sr == null || !sr.red) {
                                if (sl != null)
                                    sl.red = false;
                                xpr.red = true;
                                root = rotateRight(root, xpr);
                                xpr = (xp = x.parent) == null ?
                                        null : xp.right;
                            }
                            if (xpr != null) {
                                xpr.red = (xp == null) ? false : xp.red;
                                if ((sr = xpr.right) != null)
                                    sr.red = false;
                            }
                            if (xp != null) {
                                xp.red = false;
                                root = rotateLeft(root, xp);
                            }
                            x = root;
                        }
                    }
                }
                else { // symmetric
                    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;
                        }
                    }
                }
            }
        }

        // 循环检查树是否符合红黑树的性质,不符合则返回false
        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;
        }
    }

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值