HashMap

package com.dlq.collections.map;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Objects;

/**
 * 簡(jiǎn)單HashMap
 * @author donglq
 * @date 2017/12/11 21:35
 */
public class SimpleHashMap<K, V> implements Serializable, Cloneable {

    /**
     * 默認(rèn)初始化容量為16粒蜈,必須為2的指數(shù)
     */
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;

    /**
     * 最大容量,
     */
    static final int MAXIMUM_CAPACITY = 1 << 30;

    /**
     * 默認(rèn)加載因子
     */
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

    /**
     * 當(dāng)數(shù)組中的元素list數(shù)量大于此值時(shí)顷窒,改為使用二叉樹
     */
    static final int TREEIFY_THRESHOLD = 8;

    static final int UNTREEIFY_THRESHOLD = 6;

    /**
     * 對(duì)于數(shù)組中某個(gè)元素集合可以二叉樹化的最小數(shù)組長(zhǎng)度
     * 否則如果一個(gè)數(shù)組元素中節(jié)點(diǎn)過多的話需要調(diào)整數(shù)組長(zhǎng)度
     * 此值至少應(yīng)該是4 * TREEIFY_THRESHOLD
     * 目的是避免調(diào)整數(shù)組大小和二叉樹化之間的沖突
     */
    static final int MIN_TREEIFY_CAPACITY = 64;

    /**
     * 基本的哈希節(jié)點(diǎn),
     * @param <K>
     * @param <V>
     */
    static class Node<K,V> {
        final int hash;
        final K key;
        V value;
        SimpleHashMap.Node<K,V> next;

        Node(int hash, K key, V value, SimpleHashMap.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 SimpleHashMap.Node) {
                SimpleHashMap.Node<?,?> e = (SimpleHashMap.Node<?,?>)o;
                if (Objects.equals(key, e.getKey()) &&
                        Objects.equals(value, e.getValue()))
                    return true;
            }
            return false;
        }
    }

    /* ---------------- 靜態(tài)工具方法 -------------- */

    /**
     * 計(jì)算key的哈希值
     * 將哈希值的高16位與低16位按位做異或計(jì)算
     * 可避免由于數(shù)組長(zhǎng)度的限制導(dǎo)致哈希值的高位在數(shù)組角標(biāo)計(jì)算中不發(fā)揮作用
     * @param key
     * @return
     */
    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

    /**
     * 如果對(duì)象x的類是“class C implements Comparable<C><”這種格式恋追,則返回x的類;否則返回null
     * @param x
     * @return
     */
    static Class<?> comparableClassFor(Object x) {
        if (x instanceof Comparable) {
            Class<?> c; Type[] ts, as; ParameterizedType p;
            if ((c = x.getClass()) == String.class) // bypass checks
                return c;
            if ((ts = c.getGenericInterfaces()) != null) {
                for (Type t : ts) {
                    if ((t 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;
    }

    static int compareComparables(Class<?> kc, Object k, Object x) {
        return (x == null || x.getClass() != kc ? 0 :
                ((Comparable)k).compareTo(x));
    }

    /**
     * 對(duì)于指定的容量大小,調(diào)整為2的指數(shù)大小
     * @param cap
     * @return
     */
    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;
    }

    /* ---------------- 屬性 -------------- */

    /**
     * 存儲(chǔ)數(shù)據(jù)的數(shù)組蒋荚,在第一次使用時(shí)進(jìn)行初始化,在必要時(shí)調(diào)整數(shù)組長(zhǎng)度馆蠕,長(zhǎng)度總是2的指數(shù)
     */
    transient SimpleHashMap.Node<K,V>[] table;

    /**
     * key-value對(duì)的數(shù)量
     */
    transient int size;

    /**
     * 結(jié)構(gòu)化修改的次數(shù)
     */
    transient int modCount;

    /**
     * 下一次調(diào)整數(shù)組長(zhǎng)度的臨界值(容量 * 加載因素)
     */
    int threshold;

    /**
     * 加載因素期升,默認(rèn)為0.75
     */
    final float loadFactor;

    /* ---------------- 公共操作 -------------- */

    /**
     * 構(gòu)造空的map
     * @param initialCapacity 初始化容量
     * @param loadFactor 加載因素
     */
    public SimpleHashMap(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);
    }

    /**
     * 指定特定容量和加載因素為默認(rèn)值構(gòu)造空map
     * @param initialCapacity
     */
    public SimpleHashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }

    public SimpleHashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }

    /**
     * 返回鍵值對(duì)的容量
     * @return
     */
    public int size() {
        return size;
    }

    /**
     * 是否為空
     * @return
     */
    public boolean isEmpty() {
        return size == 0;
    }

    /**
     * 獲取key對(duì)應(yīng)的value
     * @param key
     * @return
     */
    public V get(Object key) {
        SimpleHashMap.Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }

    /**
     * 根據(jù)hash值和key獲取value
     * @param hash
     * @param key
     * @return
     */
    final SimpleHashMap.Node<K,V> getNode(int hash, Object key) {
        //數(shù)組
        SimpleHashMap.Node<K,V>[] tab;
        //first是通過hash值定位到的數(shù)組元素中列表(或二叉樹)的第一個(gè)元素;e是遍歷的元素
        SimpleHashMap.Node<K,V> first, e;
        //數(shù)組長(zhǎng)度
        int n;
        //鍵
        K k;
        //tab[(n - 1) & hash]作用:哈希值與數(shù)組角標(biāo)按位與定位到哈希值對(duì)應(yīng)的數(shù)組元素
        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;
            if ((e = first.next) != null) {
                if (first instanceof SimpleHashMap.TreeNode) //如果節(jié)點(diǎn)數(shù)二叉樹節(jié)點(diǎn)類型互躬,則查找二叉樹節(jié)點(diǎn)
                    return ((SimpleHashMap.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;
    }

    /**
     * 是否包含key
     * @param key
     * @return
     */
    public boolean containsKey(Object key) {
        return getNode(hash(key), key) != null;
    }

    /**
     * 存儲(chǔ)
     * @param key
     * @param value
     * @return
     */
    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

    /**
     * 存儲(chǔ)
     * @param hash
     * @param key
     * @param value
     * @param onlyIfAbsent
     * @param evict
     * @return
     */
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {

        SimpleHashMap.Node<K,V>[] tab;
        //hash值對(duì)應(yīng)數(shù)組元素
        SimpleHashMap.Node<K,V> p;
        //n是數(shù)組長(zhǎng)度播赁;i是hash值對(duì)應(yīng)的數(shù)組角標(biāo)
        int n, i;
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        if ((p = tab[i = (n - 1) & hash]) == null) //第一個(gè)節(jié)點(diǎn)為空,則新建節(jié)點(diǎn)
            tab[i] = newNode(hash, key, value, null);
        else {
            //第一個(gè)節(jié)點(diǎn)不為空分三種情況:
            //1. 只有一個(gè)節(jié)點(diǎn)
            //2. 超過8個(gè)節(jié)點(diǎn)吼渡,數(shù)組元素為二叉樹
            //3. 小于8個(gè)節(jié)點(diǎn)容为,數(shù)組元素為列表
            SimpleHashMap.Node<K,V> e; K k;
            if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            else if (p instanceof SimpleHashMap.TreeNode)
                e = ((SimpleHashMap.TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                        //list中不存在這個(gè)key,則新建節(jié)點(diǎn)
                        p.next = newNode(hash, key, value, null);
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    if (e.hash == hash &&
                            ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            //數(shù)組元素中存在這個(gè)key寺酪,則更新key的值
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

    /**
     * 調(diào)整數(shù)組大小
     * @return
     */
    final SimpleHashMap.Node<K,V>[] resize() {
        SimpleHashMap.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;
            }
            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
            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"})
        SimpleHashMap.Node<K,V>[] newTab = (SimpleHashMap.Node<K,V>[])new SimpleHashMap.Node[newCap];
        table = newTab;
        if (oldTab != null) {
            for (int j = 0; j < oldCap; ++j) {
                SimpleHashMap.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 SimpleHashMap.TreeNode)
                        ((SimpleHashMap.TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                    else { // preserve order
                        SimpleHashMap.Node<K,V> loHead = null, loTail = null;
                        SimpleHashMap.Node<K,V> hiHead = null, hiTail = null;
                        SimpleHashMap.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;
    }

    SimpleHashMap.Node<K,V> newNode(int hash, K key, V value, SimpleHashMap.Node<K,V> next) {
        return new SimpleHashMap.Node<>(hash, key, value, next);
    }

    final void treeifyBin(SimpleHashMap.Node<K,V>[] tab, int hash) {
        int n, index; SimpleHashMap.Node<K,V> e;
        if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
            resize();
        else if ((e = tab[index = (n - 1) & hash]) != null) {
            SimpleHashMap.TreeNode<K,V> hd = null, tl = null;
            do {
                SimpleHashMap.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);
        }
    }

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

    SimpleHashMap.Node<K,V> replacementNode(SimpleHashMap.Node<K,V> p, SimpleHashMap.Node<K,V> next) {
        return new SimpleHashMap.Node<>(p.hash, p.key, p.value, next);
    }

    SimpleHashMap.TreeNode<K,V> newTreeNode(int hash, K key, V value, SimpleHashMap.Node<K,V> next) {
        return new SimpleHashMap.TreeNode<>(hash, key, value, next);
    }

    void afterNodeAccess(SimpleHashMap.Node<K,V> p) { }
    void afterNodeInsertion(boolean evict) { }
    void afterNodeRemoval(SimpleHashMap.Node<K,V> p) { }
    /*---------------------------二叉樹節(jié)點(diǎn)---------------------------*/

    static final class TreeNode<K,V> extends SimpleHashMap.Node<K, V> {
        SimpleHashMap.TreeNode<K,V> parent;  // red-black tree links
        SimpleHashMap.TreeNode<K,V> left;
        SimpleHashMap.TreeNode<K,V> right;
        SimpleHashMap.TreeNode<K,V> prev;    // needed to unlink next upon deletion
        boolean red;
        TreeNode(int hash, K key, V val, SimpleHashMap.Node<K,V> next) {
            super(hash, key, val, next);
        }

        /**
         * Returns root of tree containing this node.
         */
        final SimpleHashMap.TreeNode<K,V> root() {
            for (SimpleHashMap.TreeNode<K,V> r = this, p;;) {
                if ((p = r.parent) == null)
                    return r;
                r = p;
            }
        }

        /**
         * Ensures that the given root is the first node of its bin.
         */
        static <K,V> void moveRootToFront(SimpleHashMap.Node<K,V>[] tab, SimpleHashMap.TreeNode<K,V> root) {
            int n;
            if (root != null && tab != null && (n = tab.length) > 0) {
                int index = (n - 1) & root.hash;
                SimpleHashMap.TreeNode<K,V> first = (SimpleHashMap.TreeNode<K,V>)tab[index];
                if (root != first) {
                    SimpleHashMap.Node<K,V> rn;
                    tab[index] = root;
                    SimpleHashMap.TreeNode<K,V> rp = root.prev;
                    if ((rn = root.next) != null)
                        ((SimpleHashMap.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);
            }
        }

        /**
         * Finds the node starting at root p with the given hash and key.
         * The kc argument caches comparableClassFor(key) upon first use
         * comparing keys.
         */
        final SimpleHashMap.TreeNode<K,V> find(int h, Object k, Class<?> kc) {
            SimpleHashMap.TreeNode<K,V> p = this;
            do {
                int ph, dir; K pk;
                SimpleHashMap.TreeNode<K,V> pl = p.left, pr = p.right, q;
                if ((ph = p.hash) > h)
                    p = pl;
                else if (ph < h)
                    p = pr;
                else if ((pk = p.key) == k || (k != null && k.equals(pk)))
                    return p;
                else if (pl == null)
                    p = pr;
                else if (pr == null)
                    p = pl;
                else if ((kc != null ||
                        (kc = comparableClassFor(k)) != null) &&
                        (dir = compareComparables(kc, k, pk)) != 0)
                    p = (dir < 0) ? pl : pr;
                else if ((q = pr.find(h, k, kc)) != null)
                    return q;
                else
                    p = pl;
            } while (p != null);
            return null;
        }

        /**
         * Calls find for root node.
         */
        final SimpleHashMap.TreeNode<K,V> getTreeNode(int h, Object k) {
            return ((parent != null) ? root() : this).find(h, k, null);
        }

        /**
         * Tie-breaking utility for ordering insertions when equal
         * hashCodes and non-comparable. We don't require a total
         * order, just a consistent insertion rule to maintain
         * equivalence across rebalancings. Tie-breaking further than
         * necessary simplifies testing a bit.
         */
        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;
        }

        /**
         * Forms tree of the nodes linked from this node.
         * @return root of tree
         */
        final void treeify(SimpleHashMap.Node<K,V>[] tab) {
            SimpleHashMap.TreeNode<K,V> root = null;
            for (SimpleHashMap.TreeNode<K,V> x = this, next; x != null; x = next) {
                next = (SimpleHashMap.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 (SimpleHashMap.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)
                            dir = tieBreakOrder(k, pk);

                        SimpleHashMap.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);
        }

        /**
         * Returns a list of non-TreeNodes replacing those linked from
         * this node.
         */
        final SimpleHashMap.Node<K,V> untreeify(SimpleHashMap<K,V> map) {
            SimpleHashMap.Node<K,V> hd = null, tl = null;
            for (SimpleHashMap.Node<K,V> q = this; q != null; q = q.next) {
                SimpleHashMap.Node<K,V> p = map.replacementNode(q, null);
                if (tl == null)
                    hd = p;
                else
                    tl.next = p;
                tl = p;
            }
            return hd;
        }

        /**
         * Tree version of putVal.
         */
        final SimpleHashMap.TreeNode<K,V> putTreeVal(SimpleHashMap<K,V> map, SimpleHashMap.Node<K,V>[] tab,
                                               int h, K k, V v) {
            Class<?> kc = null;
            boolean searched = false;
            SimpleHashMap.TreeNode<K,V> root = (parent != null) ? root() : this;
            for (SimpleHashMap.TreeNode<K,V> p = root;;) {
                int dir, ph; K pk;
                if ((ph = p.hash) > h)
                    dir = -1;
                else if (ph < h)
                    dir = 1;
                else if ((pk = p.key) == k || (k != null && k.equals(pk)))
                    return p;
                else if ((kc == null &&
                        (kc = comparableClassFor(k)) == null) ||
                        (dir = compareComparables(kc, k, pk)) == 0) {
                    if (!searched) {
                        SimpleHashMap.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);
                }

                SimpleHashMap.TreeNode<K,V> xp = p;
                if ((p = (dir <= 0) ? p.left : p.right) == null) {
                    SimpleHashMap.Node<K,V> xpn = xp.next;
                    SimpleHashMap.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)
                        ((SimpleHashMap.TreeNode<K,V>)xpn).prev = x;
                    moveRootToFront(tab, balanceInsertion(root, x));
                    return null;
                }
            }
        }

        /**
         * Removes the given node, that must be present before this call.
         * This is messier than typical red-black deletion code because we
         * cannot swap the contents of an interior node with a leaf
         * successor that is pinned by "next" pointers that are accessible
         * independently during traversal. So instead we swap the tree
         * linkages. If the current tree appears to have too few nodes,
         * the bin is converted back to a plain bin. (The test triggers
         * somewhere between 2 and 6 nodes, depending on tree structure).
         */
        final void removeTreeNode(SimpleHashMap<K,V> map, SimpleHashMap.Node<K,V>[] tab,
                                  boolean movable) {
            int n;
            if (tab == null || (n = tab.length) == 0)
                return;
            int index = (n - 1) & hash;
            SimpleHashMap.TreeNode<K,V> first = (SimpleHashMap.TreeNode<K,V>)tab[index], root = first, rl;
            SimpleHashMap.TreeNode<K,V> succ = (SimpleHashMap.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;
            }
            SimpleHashMap.TreeNode<K,V> p = this, pl = left, pr = right, replacement;
            if (pl != null && pr != null) {
                SimpleHashMap.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
                SimpleHashMap.TreeNode<K,V> sr = s.right;
                SimpleHashMap.TreeNode<K,V> pp = p.parent;
                if (s == pr) { // p was s's direct parent
                    p.parent = s;
                    s.right = p;
                }
                else {
                    SimpleHashMap.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) {
                SimpleHashMap.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;
            }

            SimpleHashMap.TreeNode<K,V> r = p.red ? root : balanceDeletion(root, replacement);

            if (replacement == p) {  // detach
                SimpleHashMap.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(SimpleHashMap<K,V> map, SimpleHashMap.Node<K,V>[] tab, int index, int bit) {
            SimpleHashMap.TreeNode<K,V> b = this;
            // Relink into lo and hi lists, preserving order
            SimpleHashMap.TreeNode<K,V> loHead = null, loTail = null;
            SimpleHashMap.TreeNode<K,V> hiHead = null, hiTail = null;
            int lc = 0, hc = 0;
            for (SimpleHashMap.TreeNode<K,V> e = b, next; e != null; e = next) {
                next = (SimpleHashMap.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);
                }
            }
        }

        /* ------------------------------------------------------------ */
        // Red-black tree methods, all adapted from CLR

        static <K,V> SimpleHashMap.TreeNode<K,V> rotateLeft(SimpleHashMap.TreeNode<K,V> root,
                                                      SimpleHashMap.TreeNode<K,V> p) {
            SimpleHashMap.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;
        }

        static <K,V> SimpleHashMap.TreeNode<K,V> rotateRight(SimpleHashMap.TreeNode<K,V> root,
                                                       SimpleHashMap.TreeNode<K,V> p) {
            SimpleHashMap.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> SimpleHashMap.TreeNode<K,V> balanceInsertion(SimpleHashMap.TreeNode<K,V> root,
                                                            SimpleHashMap.TreeNode<K,V> x) {
            x.red = true;
            for (SimpleHashMap.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> SimpleHashMap.TreeNode<K,V> balanceDeletion(SimpleHashMap.TreeNode<K,V> root,
                                                           SimpleHashMap.TreeNode<K,V> x) {
            for (SimpleHashMap.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 {
                        SimpleHashMap.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 {
                        SimpleHashMap.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;
                        }
                    }
                }
            }
        }

        /**
         * Recursive invariant check
         */
        static <K,V> boolean checkInvariants(SimpleHashMap.TreeNode<K,V> t) {
            SimpleHashMap.TreeNode<K,V> tp = t.parent, tl = t.left, tr = t.right,
                    tb = t.prev, tn = (SimpleHashMap.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;
        }
    }
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末坎背,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子寄雀,更是在濱河造成了極大的恐慌得滤,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,204評(píng)論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件盒犹,死亡現(xiàn)場(chǎng)離奇詭異懂更,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)急膀,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,091評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門沮协,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人卓嫂,你說我怎么就攤上這事慷暂。” “怎么了晨雳?”我有些...
    開封第一講書人閱讀 164,548評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵行瑞,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我悍募,道長(zhǎng)蘑辑,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,657評(píng)論 1 293
  • 正文 為了忘掉前任坠宴,我火速辦了婚禮,結(jié)果婚禮上绷旗,老公的妹妹穿的比我還像新娘喜鼓。我一直安慰自己副砍,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,689評(píng)論 6 392
  • 文/花漫 我一把揭開白布庄岖。 她就那樣靜靜地躺著豁翎,像睡著了一般。 火紅的嫁衣襯著肌膚如雪隅忿。 梳的紋絲不亂的頭發(fā)上心剥,一...
    開封第一講書人閱讀 51,554評(píng)論 1 305
  • 那天,我揣著相機(jī)與錄音背桐,去河邊找鬼优烧。 笑死,一個(gè)胖子當(dāng)著我的面吹牛链峭,可吹牛的內(nèi)容都是我干的畦娄。 我是一名探鬼主播,決...
    沈念sama閱讀 40,302評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼弊仪,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼熙卡!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起励饵,我...
    開封第一講書人閱讀 39,216評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤驳癌,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后役听,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體喂柒,經(jīng)...
    沈念sama閱讀 45,661評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,851評(píng)論 3 336
  • 正文 我和宋清朗相戀三年禾嫉,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了灾杰。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,977評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡熙参,死狀恐怖艳吠,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情孽椰,我是刑警寧澤昭娩,帶...
    沈念sama閱讀 35,697評(píng)論 5 347
  • 正文 年R本政府宣布,位于F島的核電站黍匾,受9級(jí)特大地震影響栏渺,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜锐涯,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,306評(píng)論 3 330
  • 文/蒙蒙 一磕诊、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦霎终、人聲如沸滞磺。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,898評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)击困。三九已至,卻和暖如春广凸,著一層夾襖步出監(jiān)牢的瞬間阅茶,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,019評(píng)論 1 270
  • 我被黑心中介騙來泰國(guó)打工谅海, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留脸哀,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,138評(píng)論 3 370
  • 正文 我出身青樓胁赢,卻偏偏與公主長(zhǎng)得像企蹭,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子智末,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,927評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容