手写HashMap(JDK8)第二天

一,HashMap红黑树基本概念理解

左旋右旋-动态演示
树的左旋右旋 , 多层左旋右旋
红黑平衡 ,红黑树修改平衡
更详细的可参见《算法导论》。

二,实现内容一览

昨天实现了HashMap的基本创建和链表结构存储数据,这是JDK1.8之前的数据结构。在JDK1.8之后,HashMap引入了红黑树的概念,当链表长度超过一定值时,默认为8,就会将链表转换为红黑树。

几个重要参数:

    //链表转红黑树阙值
    static final int TREEIFY_THRESHOLD = 8;

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

    //链表转红黑树时,检查集合容量的阙值,最小不能低于该值
    static final int MIN_TREEIFY_CAPACITY = 64;

红黑树一个重要的类: TreeNode
该类是HashMap中的一个静态内部类,也是红黑树的核心实现。该类包含了红黑树的所有操作,看一下类结构。

   static final class TreeNode extends ImitatedWritingHashMap.Entry{
        ImitatedWritingHashMap.TreeNode parent;
        ImitatedWritingHashMap.TreeNode left;
        ImitatedWritingHashMap.TreeNode right;
        ImitatedWritingHashMap.TreeNode prev;
        boolean red;
        TreeNode(int hash, K key, V value, Node next) {
            super(hash, key, value, next);
        }

        //求根节点
        final ImitatedWritingHashMap.TreeNode root() ;

        //确保根节点是链表的第一个节点
        static  void moveRootToFront(ImitatedWritingHashMap.Node[] tab, ImitatedWritingHashMap.TreeNode root);

        //查找树节点
        final ImitatedWritingHashMap.TreeNode find(int h, Object k, Class kc) ;

        //获取树节点
        final ImitatedWritingHashMap.TreeNode getTreeNode(int h, Object k) ;

        //
        static int tieBreakOrder(Object a, Object b) ;

        //链表转化为红黑树
        final void treeify(ImitatedWritingHashMap.Node[] tab);

        //向红黑树插入节点
        final ImitatedWritingHashMap.TreeNode putTreeVal(ImitatedWritingHashMap map, ImitatedWritingHashMap.Node[] tab,int h, K k, V v) ;

        //插入平衡
        static  ImitatedWritingHashMap.TreeNode balanceInsertion(ImitatedWritingHashMap.TreeNode root,
                                                              ImitatedWritingHashMap.TreeNode x) ;
        //左旋
        static  ImitatedWritingHashMap.TreeNode rotateLeft(ImitatedWritingHashMap.TreeNode root,
                                                        ImitatedWritingHashMap.TreeNode p) ;
        //右旋
        static  ImitatedWritingHashMap.TreeNode rotateRight(ImitatedWritingHashMap.TreeNode root,
                                                         ImitatedWritingHashMap.TreeNode p) ;
        //删除平衡
        static  ImitatedWritingHashMap.TreeNode balanceDeletion(ImitatedWritingHashMap.TreeNode root,
                                                             ImitatedWritingHashMap.TreeNode x) ;
        //树的扩容,拆分为两棵树
        final void split(ImitatedWritingHashMap map, ImitatedWritingHashMap.Node[] tab, int index, int bit) ;
               
        //红黑树转化链表
        final ImitatedWritingHashMap.Node untreeify(ImitatedWritingHashMap map) ;

    }

三,代码实现

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.*;
import java.util.logging.Logger;

public class ImitatedWritingHashMap extends AbstractMap implements Map, Cloneable, Serializable {

    static Logger logger = Logger.getLogger(ImitatedWritingHashMap.class.getName());

    //初始化容器容量,默认大小16
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;

    //最大容量,Integer.MAX_VALUE的一半,超过这个容量,
    static final int MAXIMUM_CAPACITY = 1 << 30;

    //默认容载因子,表示容器的使用情况,也是容器扩容的重要指标之一
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

    //扩容指标,容器根据该值判断是否需要扩容
    transient int threshold;

    transient final float loadFactor;

    //链表转红黑树阙值
    static final int TREEIFY_THRESHOLD = 8;

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

    //链表转红黑树时,检查集合容量的阙值,最小不能低于该值
    static final int MIN_TREEIFY_CAPACITY = 64;

    //map桶数组
    transient ImitatedWritingHashMap.Node[] table;

    transient Set> entrySet;

    //map长度
    transient int size;

    transient int modCount;
    private K key;
    private V value;

    public ImitatedWritingHashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
 
        logger.info("默认初始化构造器");
    }

    public ImitatedWritingHashMap(int initialCapacity, float loadFactor) {
        logger.info("(容器容量:+" + initialCapacity + ",容载因子:" + 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 ImitatedWritingHashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }

    //用作链表
    static class Node implements Map.Entry {
        int hash;
        K key;
        V value;
        Node next;

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

        @Override
        public K getKey() {
            return key;
        }

        @Override
        public V getValue() {
            return value;
        }

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

        @Override
        public String toString() {
            return "Node{" +
                    "key=" + key +
                    ", value=" + value +
                    '}';
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            Node node = (Node) o;
            return Objects.equals(key, node.key) &&
                    Objects.equals(value, node.value);
        }

        @Override
        public int hashCode() {
            return Objects.hash(key, value);
        }
    }

    //计算需要数组的长度
    final int tableSizeFor(int initialCapacity) {
        int n = initialCapacity - 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;
    }

    //初始化或重新规划
    ImitatedWritingHashMap.Node[] resize() {
        ImitatedWritingHashMap.Node[] 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;
            }
        } else if (oldThr > 0)
            newCap = oldThr;
        else {
            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;

        ImitatedWritingHashMap.Node[] newTab = (ImitatedWritingHashMap.Node[]) new ImitatedWritingHashMap.Node[newCap];
        table = newTab;

        //扩容原集合
        if (oldTab != null) {
            for (int j = 0; j < oldCap; ++j) {
                ImitatedWritingHashMap.Node oldNode;

                if((oldNode=oldTab[j])!=null){
                    oldTab[j] = null;

                    if (oldNode.next == null)
                        newTab[oldNode.hash & (newCap - 1)] = oldNode;
                    else if (oldNode instanceof ImitatedWritingHashMap.TreeNode){
                        ((ImitatedWritingHashMap.TreeNode)oldNode).split(this, newTab, j,  oldCap);
                    }else{
                        ImitatedWritingHashMap.Node loHead = null, loTail = null;  //
                        ImitatedWritingHashMap.Node hiHead = null, hiTail = null;
                        ImitatedWritingHashMap.Node next;
                        /**
                         * 核心难点
                         *
                         * 将链表 拆分为两个链表(这里本人也不清楚拆分成两个重新组合链表的优点,欢迎大神指点。。。)
                         */
                        do {
                            next = oldNode.next;
                            if ((oldNode.hash & oldCap) == 0) {
                                if (loTail == null)
                                    loHead = oldNode;
                                else
                                    loTail.next = oldNode;
                                loTail = oldNode;
                            }
                            else {
                                if (hiTail == null)
                                    hiHead = oldNode;
                                else
                                    hiTail.next = oldNode;
                                hiTail = oldNode;
                            }
                        } while ((oldNode = next) != null);

                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead;
                        }
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }

                }
            }
        }

        return newTab;
    }

    /**
     *
     * @param hash 哈希值
     * @param key  键值
     * @param value  值
     * @param onlyIfAbsent 如果为true,不覆盖已有的值
     * @param evict  备用,LinkedHashMap有用
     * @return
     */
    V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {
        logger.info("putVal: "+hash+","+key+","+value);
        ImitatedWritingHashMap.Node[] hashTab;
        ImitatedWritingHashMap.Node tempNode;
        int n, i;

        if ((hashTab = table) == null || (n = hashTab.length) == 0)
            n = (hashTab = resize()).length;
        if ((tempNode = hashTab[i = (n - 1) & hash]) == null)
            hashTab[i] = newNode(hash, key, value, null);
        else{
            ImitatedWritingHashMap.Node insertNode; K k;
            //找到重复项
            if (tempNode.hash == hash &&
                    ((k = tempNode.key) == key || (key != null && key.equals(k))))
                insertNode = tempNode;
            else if (tempNode instanceof ImitatedWritingHashMap.TreeNode)
                insertNode = ((ImitatedWritingHashMap.TreeNode)tempNode).putTreeVal(this, hashTab, hash, key, value);
            else{
                for (int binCount = 0; ; ++binCount) {
                    if ((insertNode = tempNode.next) == null) {
                        tempNode.next = newNode(hash, key, value, null);
                        //链表转红黑树
                        if (binCount >= TREEIFY_THRESHOLD - 1)
                            treeifyBin(hashTab, hash);
                        break;
                    }
                    if (insertNode.hash == hash &&
                            ((k = insertNode.key) == key || (key != null && key.equals(k))))
                        break;
                    tempNode = insertNode;
                }
            }

            if (insertNode != null) {
                V oldValue = insertNode.value;
                if (!onlyIfAbsent || oldValue == null)
                    insertNode.value = value;

                return oldValue;
            }

        }
        ++modCount;
        if (++size > threshold)
            resize();
        //afterNodeInsertion(evict);
        return null;
    }

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

    @Override
    public final Object put(Object k, Object v) {
        K key =(K)k;
        V value =(V)v;
        return putVal(hash(key), key, value, false, true);
    }

    @Override
    public Object get(Object key) {
        ImitatedWritingHashMap.Node e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }

    final ImitatedWritingHashMap.Node getNode(int hash, Object key) {
        ImitatedWritingHashMap.Node[] tab; ImitatedWritingHashMap.Node first, e; int n; K k;
        if ((tab = table) != null && (n = tab.length) > 0 && (first = tab[(n - 1) & hash]) != null) {
            if (first.hash == hash && ((k = first.key) == key || (key != null && key.equals(k))))
                return first;

            if ((e = first.next) != null) {
                //红黑树查找
                if (first instanceof ImitatedWritingHashMap.TreeNode)
                    return ((ImitatedWritingHashMap.TreeNode)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;
    }

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

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

    public static void main(String[] args) {
        ImitatedWritingHashMap map = new ImitatedWritingHashMap();

        for(int i=0;i<999999;i++){
            map.put("2w"+i,"2w");
        }

    }

    @Override
    public Set entrySet() {
        return null;
    }

    static class Entry extends ImitatedWritingHashMap.Node {
        ImitatedWritingHashMap.Entry before, after;
        Entry(int hash, K key, V value, ImitatedWritingHashMap.Node next) {
            super(hash, key, value, next);
        }
    }

    static final class TreeNode extends ImitatedWritingHashMap.Entry{
        ImitatedWritingHashMap.TreeNode parent;
        ImitatedWritingHashMap.TreeNode left;
        ImitatedWritingHashMap.TreeNode right;
        ImitatedWritingHashMap.TreeNode prev;
        boolean red;
        TreeNode(int hash, K key, V value, Node next) {
            super(hash, key, value, next);
        }

        //求跟节点
        final ImitatedWritingHashMap.TreeNode root() {
            for (ImitatedWritingHashMap.TreeNode r = this, p;;) {
                if ((p = r.parent) == null)
                    return r;
                r = p;
            }
        }

        //确保根节点是链表的第一个节点
        static  void moveRootToFront(ImitatedWritingHashMap.Node[] tab, ImitatedWritingHashMap.TreeNode root) {
            int n;
            if (root != null && tab != null && (n = tab.length) > 0) {
                int index = (n - 1) & root.hash;
                ImitatedWritingHashMap.TreeNode first = (ImitatedWritingHashMap.TreeNode)tab[index];
                if (root != first) {
                    ImitatedWritingHashMap.Node rn;
                    tab[index] = root;
                    ImitatedWritingHashMap.TreeNode rp = root.prev;
                    if ((rn = root.next) != null)
                        ((ImitatedWritingHashMap.TreeNode)rn).prev = rp;
                    if (rp != null)
                        rp.next = rn;
                    if (first != null)
                        first.prev = root;
                    root.next = first;
                    root.prev = null;
                }
               // assert checkInvariants(root);
            }
        }

        //查找树节点
        final ImitatedWritingHashMap.TreeNode find(int h, Object k, Class kc) {
            ImitatedWritingHashMap.TreeNode p = this;
            do {
                int ph, dir; K pk;
                ImitatedWritingHashMap.TreeNode 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;
        }

        //获取树节点
        final ImitatedWritingHashMap.TreeNode getTreeNode(int h, Object k) {
            return ((parent != null) ? root() : this).find(h, k, null);
        }

        //
        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(ImitatedWritingHashMap.Node[] tab) {
            logger.info("enter treeify");
            ImitatedWritingHashMap.TreeNode root = null;
            for (ImitatedWritingHashMap.TreeNode x = this, next; x != null; x = next) {
                next = (ImitatedWritingHashMap.TreeNode)x.next;
                x.left = x.right = null;
                if (root == null) {
                    x.parent = null;
                    x.red = false;
                    root = x;
                }
                else {

                    System.out.println("treeify else");
                    K k = x.key;
                    int h = x.hash;
                    Class kc = null;
                    for (ImitatedWritingHashMap.TreeNode 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);

                        ImitatedWritingHashMap.TreeNode 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 ImitatedWritingHashMap.TreeNode putTreeVal(ImitatedWritingHashMap map, ImitatedWritingHashMap.Node[] tab,
                                                 int h, K k, V v) {
            Class kc = null;
            boolean searched = false;
            ImitatedWritingHashMap.TreeNode root = (parent != null) ? root() : this;
            for (ImitatedWritingHashMap.TreeNode 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) {
                        ImitatedWritingHashMap.TreeNode 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);
                }

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

        //插入平衡
        static  ImitatedWritingHashMap.TreeNode balanceInsertion(ImitatedWritingHashMap.TreeNode root,
                                                              ImitatedWritingHashMap.TreeNode x) {
            x.red = true;
            for (ImitatedWritingHashMap.TreeNode 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  ImitatedWritingHashMap.TreeNode rotateLeft(ImitatedWritingHashMap.TreeNode root,
                                                        ImitatedWritingHashMap.TreeNode p) {
            ImitatedWritingHashMap.TreeNode 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  ImitatedWritingHashMap.TreeNode rotateRight(ImitatedWritingHashMap.TreeNode root,
                                                         ImitatedWritingHashMap.TreeNode p) {
            ImitatedWritingHashMap.TreeNode 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  ImitatedWritingHashMap.TreeNode balanceDeletion(ImitatedWritingHashMap.TreeNode root,
                                                             ImitatedWritingHashMap.TreeNode x) {
            for (ImitatedWritingHashMap.TreeNode 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 {
                        ImitatedWritingHashMap.TreeNode 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 {
                        ImitatedWritingHashMap.TreeNode 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;
                        }
                    }
                }
            }
        }

        //树的扩容,拆分为两棵树
        final void split(ImitatedWritingHashMap map, ImitatedWritingHashMap.Node[] tab, int index, int bit) {
            ImitatedWritingHashMap.TreeNode b = this;

            ImitatedWritingHashMap.TreeNode loHead = null, loTail = null;
            ImitatedWritingHashMap.TreeNode hiHead = null, hiTail = null;
            int lc = 0, hc = 0;
            for (ImitatedWritingHashMap.TreeNode e = b, next; e != null; e = next) {
                next = (ImitatedWritingHashMap.TreeNode)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)
                        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);
                }
            }
        }

        //红黑树转化链表
        final ImitatedWritingHashMap.Node untreeify(ImitatedWritingHashMap map) {
            ImitatedWritingHashMap.Node hd = null, tl = null;
            for (ImitatedWritingHashMap.Node q = this; q != null; q = q.next) {
                ImitatedWritingHashMap.Node p = map.replacementNode(q, null);
                if (tl == null)
                    hd = p;
                else
                    tl.next = p;
                tl = p;
            }
            return hd;
        }

    }
    static int compareComparables(Class kc, Object k, Object x) {

        return (x == null || x.getClass() != kc ? 0 :
                ((Comparable)k).compareTo(x));
    }

    static Class comparableClassFor(Object object) {
        if(object instanceof Comparable){
            Class c; Type[] ts, as; Type t; ParameterizedType p;
            if ((c = object.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)
                        return c;
                }
            }
        }
        return null;
    }


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

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

    //链表节点转换为树节点
    ImitatedWritingHashMap.TreeNode replacementTreeNode(ImitatedWritingHashMap.Node p, ImitatedWritingHashMap.Node next) {
        return new ImitatedWritingHashMap.TreeNode<>(p.hash, p.key, p.value, next);
    }
}

你可能感兴趣的:(源码)