HashMap

作者: donglq | 来源:发表于2017-12-11 23:46 被阅读0次
    package com.dlq.collections.map;
    
    import java.io.Serializable;
    import java.lang.reflect.ParameterizedType;
    import java.lang.reflect.Type;
    import java.util.Objects;
    
    /**
     * 简单HashMap
     * @author donglq
     * @date 2017/12/11 21:35
     */
    public class SimpleHashMap<K, V> implements Serializable, Cloneable {
    
        /**
         * 默认初始化容量为16,必须为2的指数
         */
        static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
    
        /**
         * 最大容量,
         */
        static final int MAXIMUM_CAPACITY = 1 << 30;
    
        /**
         * 默认加载因子
         */
        static final float DEFAULT_LOAD_FACTOR = 0.75f;
    
        /**
         * 当数组中的元素list数量大于此值时,改为使用二叉树
         */
        static final int TREEIFY_THRESHOLD = 8;
    
        static final int UNTREEIFY_THRESHOLD = 6;
    
        /**
         * 对于数组中某个元素集合可以二叉树化的最小数组长度
         * 否则如果一个数组元素中节点过多的话需要调整数组长度
         * 此值至少应该是4 * TREEIFY_THRESHOLD
         * 目的是避免调整数组大小和二叉树化之间的冲突
         */
        static final int MIN_TREEIFY_CAPACITY = 64;
    
        /**
         * 基本的哈希节点,
         * @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;
            }
        }
    
        /* ---------------- 静态工具方法 -------------- */
    
        /**
         * 计算key的哈希值
         * 将哈希值的高16位与低16位按位做异或计算
         * 可避免由于数组长度的限制导致哈希值的高位在数组角标计算中不发挥作用
         * @param key
         * @return
         */
        static final int hash(Object key) {
            int h;
            return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
        }
    
        /**
         * 如果对象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));
        }
    
        /**
         * 对于指定的容量大小,调整为2的指数大小
         * @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;
        }
    
        /* ---------------- 属性 -------------- */
    
        /**
         * 存储数据的数组,在第一次使用时进行初始化,在必要时调整数组长度,长度总是2的指数
         */
        transient SimpleHashMap.Node<K,V>[] table;
    
        /**
         * key-value对的数量
         */
        transient int size;
    
        /**
         * 结构化修改的次数
         */
        transient int modCount;
    
        /**
         * 下一次调整数组长度的临界值(容量 * 加载因素)
         */
        int threshold;
    
        /**
         * 加载因素,默认为0.75
         */
        final float loadFactor;
    
        /* ---------------- 公共操作 -------------- */
    
        /**
         * 构造空的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);
        }
    
        /**
         * 指定特定容量和加载因素为默认值构造空map
         * @param initialCapacity
         */
        public SimpleHashMap(int initialCapacity) {
            this(initialCapacity, DEFAULT_LOAD_FACTOR);
        }
    
        public SimpleHashMap() {
            this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
        }
    
        /**
         * 返回键值对的容量
         * @return
         */
        public int size() {
            return size;
        }
    
        /**
         * 是否为空
         * @return
         */
        public boolean isEmpty() {
            return size == 0;
        }
    
        /**
         * 获取key对应的value
         * @param key
         * @return
         */
        public V get(Object key) {
            SimpleHashMap.Node<K,V> e;
            return (e = getNode(hash(key), key)) == null ? null : e.value;
        }
    
        /**
         * 根据hash值和key获取value
         * @param hash
         * @param key
         * @return
         */
        final SimpleHashMap.Node<K,V> getNode(int hash, Object key) {
            //数组
            SimpleHashMap.Node<K,V>[] tab;
            //first是通过hash值定位到的数组元素中列表(或二叉树)的第一个元素;e是遍历的元素
            SimpleHashMap.Node<K,V> first, e;
            //数组长度
            int n;
            //键
            K k;
            //tab[(n - 1) & hash]作用:哈希值与数组角标按位与定位到哈希值对应的数组元素
            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) //如果节点数二叉树节点类型,则查找二叉树节点
                        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;
        }
    
        /**
         * 存储
         * @param key
         * @param value
         * @return
         */
        public V put(K key, V value) {
            return putVal(hash(key), key, value, false, true);
        }
    
        /**
         * 存储
         * @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值对应数组元素
            SimpleHashMap.Node<K,V> p;
            //n是数组长度;i是hash值对应的数组角标
            int n, i;
            if ((tab = table) == null || (n = tab.length) == 0)
                n = (tab = resize()).length;
            if ((p = tab[i = (n - 1) & hash]) == null) //第一个节点为空,则新建节点
                tab[i] = newNode(hash, key, value, null);
            else {
                //第一个节点不为空分三种情况:
                //1. 只有一个节点
                //2. 超过8个节点,数组元素为二叉树
                //3. 小于8个节点,数组元素为列表
                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中不存在这个key,则新建节点
                            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;
                    }
                }
                //数组元素中存在这个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;
        }
    
        /**
         * 调整数组大小
         * @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) { }
        /*---------------------------二叉树节点---------------------------*/
    
        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;
            }
        }
    }
    
    

    相关文章

      网友评论

          本文标题:HashMap

          本文链接:https://www.haomeiwen.com/subject/jrxgixtx.html