JDK8 TreeMap源码浅析

增加元素

    public V put(K key, V value) {
        Entry<K,V> t = root;
		
        if (t == null) {
		
			// 空树,直接插入并结束
		
            compare(key, key); // type (and possibly null) check

            root = new Entry<>(key, value, null);
            size = 1;
            modCount++;
            return null;
        }
		
		// 不是空树
		
        int cmp; // 记录比较大小的结果
        Entry<K,V> parent; // 新节点的父节点
		
        // split comparator and comparable paths
        Comparator<? super K> cpr = comparator; // comparator是构造TreeMap时传入的比较逻辑,如果不传则为null
		
        if (cpr != null) {
		
			// 使用显式指定的comparator
		
            do {
                parent = t;
                cmp = cpr.compare(key, t.key);
                if (cmp < 0)
                    t = t.left;
                else if (cmp > 0)
                    t = t.right;
                else
                    return t.setValue(value); // 找到key值一样的节点后直接替换对应的value
            } while (t != null);
        }
		
        else {
		
			// 没有指定comparator,则假设key实现了Comparable接口
		
            if (key == null)
                throw new NullPointerException();
				
            @SuppressWarnings("unchecked")
                Comparable<? super K> k = (Comparable<? super K>) key; // 若key没有实现Comparable接口则抛异常
				
            do {
                parent = t;
                cmp = k.compareTo(t.key);
                if (cmp < 0)
                    t = t.left;
                else if (cmp > 0)
                    t = t.right;
                else
                    return t.setValue(value);
            } while (t != null);
        }
		
		// 插入新节点
		
        Entry<K,V> e = new Entry<>(key, value, parent);
        if (cmp < 0)
            parent.left = e;
        else
            parent.right = e;
			
        fixAfterInsertion(e); // 调整
		
        size++;
        modCount++;
        return null;
    }
    /** From CLR */
    private void fixAfterInsertion(Entry<K,V> x) {
        x.color = RED; // 新节点都是红色

        while (x != null && x != root && x.parent.color == RED) { // x.parent.color == RED:父节点是红色才需要调整
            if (parentOf(x) == leftOf(parentOf(parentOf(x)))) {
			
				// 父节点是祖父节点的左孩子
			
                Entry<K,V> y = rightOf(parentOf(parentOf(x))); // 叔叔节点
				
                if (colorOf(y) == RED) {
				
					// 叔叔节点是红色
				
                    setColor(parentOf(x), BLACK); // 把父节点设为黑色
                    setColor(y, BLACK); // 把叔叔节点设为黑色
                    setColor(parentOf(parentOf(x)), RED); // 把祖父节点设为红色
                    x = parentOf(parentOf(x)); // 把祖父节点视为新节点继续操作
                } 
				
				else {
				
					// 叔叔节点是黑色或者不存在
				
                    if (x == rightOf(parentOf(x))) {
					
						// 新节点是父节点的右孩子(即LR),先对父节点进行左旋操作,从而转化为LL
					
                        x = parentOf(x);
                        rotateLeft(x);
                    }
					
					// LL
					
                    setColor(parentOf(x), BLACK); // 把父节点设为黑色
                    setColor(parentOf(parentOf(x)), RED); // 把祖父节点设为红色
                    rotateRight(parentOf(parentOf(x))); // 对父节点进行右旋操作
                }
            } 
			
			else {
			
				// 父节点是祖父节点的右孩子
			
                Entry<K,V> y = leftOf(parentOf(parentOf(x)));
                if (colorOf(y) == RED) {
                    setColor(parentOf(x), BLACK);
                    setColor(y, BLACK);
                    setColor(parentOf(parentOf(x)), RED);
                    x = parentOf(parentOf(x));
                } else {
                    if (x == leftOf(parentOf(x))) {
                        x = parentOf(x);
                        rotateRight(x);
                    }
                    setColor(parentOf(x), BLACK);
                    setColor(parentOf(parentOf(x)), RED);
                    rotateLeft(parentOf(parentOf(x)));
                }
            }
        }
		
        root.color = BLACK; // x可能是根节点,也可能是红色,反正把x设为黑色总是对的
    }

删除元素

    /**
     * Delete node p, and then rebalance the tree.
     */
    private void deleteEntry(Entry<K,V> p) {
        modCount++;
        size--;

        // If strictly internal, copy successor's element to p and then make p
        // point to successor.
        if (p.left != null && p.right != null) {
            Entry<K,V> s = successor(p);
            p.key = s.key;
            p.value = s.value;
            p = s;
        } // p has 2 children

        // Start fixup at replacement node, if it exists.
        Entry<K,V> replacement = (p.left != null ? p.left : p.right);

		// p代表要删除的节点,replacement是p的孩子,用来替代p
		
        if (replacement != null) {
		
			// p有一个孩子 => p是黑色,replacement是红色
		
            // Link replacement to parent
            replacement.parent = p.parent;
			
			/* 用replacement替代p */
			
            if (p.parent == null)
			
				// p是根节点
			
                root = replacement;
				
            else if (p == p.parent.left)
                p.parent.left  = replacement;
				
            else
                p.parent.right = replacement;

            // Null out links so they are OK to use by fixAfterDeletion.
            p.left = p.right = p.parent = null;

            // Fix replacement
            if (p.color == BLACK)
				// 黑色才需要调整,但在这里似乎必然成立,简单地把replacement设为黑色即可
                fixAfterDeletion(replacement);
        } 
		
		else if (p.parent == null) { // return if we are the only node.
            root = null;
        } 
		
		else { //  No children. Use self as phantom replacement and unlink.
		
			// p是叶子节点
		
            if (p.color == BLACK)
				// 黑色才需要调整
                fixAfterDeletion(p);

            if (p.parent != null) {
                if (p == p.parent.left)
                    p.parent.left = null;
                else if (p == p.parent.right)
                    p.parent.right = null;
                p.parent = null; // help GC
            }
        }
    }
    /**
	 * Returns the successor of the specified Entry, or null if no such.
	 *
     * 后继节点首选是“右边最远的左下”子孙节点,其次是“最近的右上”祖先节点
     */
    static <K,V> TreeMap.Entry<K,V> successor(Entry<K,V> t) {
        if (t == null)
            return null;
        else if (t.right != null) {
		
			// 寻找“右边最远的左下”子孙节点
		
			// 因为本方法被deleteEntry调用之前,deleteEntry对右孩子是否为空进行了判断,所以肯定走这里
		
            Entry<K,V> p = t.right;
            while (p.left != null)
                p = p.left;
            return p;
        } else {
		
			// 寻找“最近的右上”祖先节点
		
            Entry<K,V> p = t.parent;
            Entry<K,V> ch = t;
            while (p != null && ch == p.right) {
                ch = p;
                p = p.parent;
            }
            return p;
        }
    }
    /** From CLR */
    private void fixAfterDeletion(Entry<K,V> x) {
        while (x != root && colorOf(x) == BLACK) { // 黑色才需要调整
            if (x == leftOf(parentOf(x))) {
			
				// x是左孩子
			
                Entry<K,V> sib = rightOf(parentOf(x)); // sib代表x的兄弟节点,是右孩子

                if (colorOf(sib) == RED) {
				
					// 兄弟节点是红色
				
                    setColor(sib, BLACK);
                    setColor(parentOf(x), RED);
                    rotateLeft(parentOf(x));
                    sib = rightOf(parentOf(x)); // 更新sib,sib依然代表x的兄弟节点,是右孩子
                }
				
				// 兄弟节点是黑色
				
                if (colorOf(leftOf(sib))  == BLACK &&
                    colorOf(rightOf(sib)) == BLACK) {
					
					// 兄弟节点的两个孩子都是黑色
					
                    setColor(sib, RED); // 把兄弟节点设为红色
                    x = parentOf(x);
                } 
				
				else {
				
					// 兄弟节点有红色孩子
				
                    if (colorOf(rightOf(sib)) == BLACK) { // 看看是否RL 
						
						// 当前是RL,需要调整为RR
					
                        setColor(leftOf(sib), BLACK);
                        setColor(sib, RED);
                        rotateRight(sib);
                        sib = rightOf(parentOf(x));
                    }
					
					// 当前是RR
					
                    setColor(sib, colorOf(parentOf(x)));
                    setColor(parentOf(x), BLACK);
                    setColor(rightOf(sib), BLACK);
                    rotateLeft(parentOf(x));
                    x = root; // 用于退出循环
                }
            } 
			
			else { // symmetric
                Entry<K,V> sib = leftOf(parentOf(x));

                if (colorOf(sib) == RED) {
                    setColor(sib, BLACK);
                    setColor(parentOf(x), RED);
                    rotateRight(parentOf(x));
                    sib = leftOf(parentOf(x));
                }

                if (colorOf(rightOf(sib)) == BLACK &&
                    colorOf(leftOf(sib)) == BLACK) {
                    setColor(sib, RED);
                    x = parentOf(x);
                } else {
                    if (colorOf(leftOf(sib)) == BLACK) {
                        setColor(rightOf(sib), BLACK);
                        setColor(sib, RED);
                        rotateLeft(sib);
                        sib = leftOf(parentOf(x));
                    }
                    setColor(sib, colorOf(parentOf(x)));
                    setColor(parentOf(x), BLACK);
                    setColor(leftOf(sib), BLACK);
                    rotateRight(parentOf(x));
                    x = root;
                }
            }
        }

        setColor(x, BLACK); // x可能是根节点,也可能是红色,反正把x设为黑色总是对的
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值