JDK1.8 TreeMap源码分析

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/MrLiar17/article/details/85053276

TreeMap是通过红黑树实现的,增删改查的操作底层都是对红黑树的相关操作,因此先介绍红黑树的相关性质。

红黑树顾名思义就是节点是红色或者黑色的平衡二叉树,它通过颜色的约束来维持着二叉树的平衡。对于一棵有效的红黑树二叉树而言我们必须增加如下规则:

     1、每个节点都只能是红色或者黑色
     2、根节点是黑色
     3、每个叶节点(null节点,空节点)是黑色的。
     4、如果一个结点是红的,则它两个子节点都是黑的。也就是说在一条路径上不能出现相邻的两个红色结点。
     5、从任一节点到其每个叶子的所有路径都包含相同数目的黑色节点。

1、TreeMap继承关系

public class TreeMap<K,V>
    extends AbstractMap<K,V>  //继承AbstractMap,实现NavigableMap
    implements NavigableMap<K,V>, Cloneable, java.io.Serializable

NavigableMap接口继承了SortedMap。

2、参数信息

    private final Comparator<? super K> comparator;//比较器
    private transient Entry<K,V> root;//根节点
    /**
     * The number of entries in the tree
     */
    private transient int size = 0;///TreeMap大小
    /**
     * The number of structural modifications to the tree.
     */
    private transient int modCount = 0;//修改结构次数

3、构造函数

    public TreeMap() {//无参构造函数
        comparator = null;
    }

    public TreeMap(Comparator<? super K> comparator) {//带比较器的构造函数
        this.comparator = comparator;
    }
 
    public TreeMap(Map<? extends K, ? extends V> m) {//Map的构造函数,Map成为TreeMap的子集
        comparator = null;
        putAll(m);
    }
   
    public TreeMap(SortedMap<K, ? extends V> m) {//带SortedMap的构造函数
        comparator = m.comparator();
        try {
            buildFromSorted(m.size(), m.entrySet().iterator(), null, null);
        } catch (java.io.IOException cannotHappen) {
        } catch (ClassNotFoundException cannotHappen) {
        }
    }

4、get方法

public V get(Object key) { 
        Entry<K,V> p = getEntry(key);//调用getEntry方法
        return (p==null ? null : p.value);
}

4.1 getEntry方法

    final Entry<K,V> getEntry(Object key) {
        // Offload comparator-based version for sake of performance
        if (comparator != null)//判断是否实现了比较器
            return getEntryUsingComparator(key);//调用getEntryUsingComparator
        if (key == null)
            throw new NullPointerException();//treeMap不能存储null key键
        @SuppressWarnings("unchecked")
            Comparable<? super K> k = (Comparable<? super K>) key;//key值
        Entry<K,V> p = root;//根节点
        while (p != null) {//循环遍历树
            int cmp = k.compareTo(p.key);
            if (cmp < 0)//左子树遍历
                p = p.left;
            else if (cmp > 0)//右子树遍历
                p = p.right;
            else
                return p;//key值相等,返回数据
        }
        return null;//否则返回null值
    }

4.2 getEntryUsingComparator方法

    final Entry<K,V> getEntryUsingComparator(Object key) {
        @SuppressWarnings("unchecked")
            K k = (K) key;
        Comparator<? super K> cpr = comparator;//用自己比较器
        if (cpr != null) {
            Entry<K,V> p = root;//树根节点
            while (p != null) {//循环遍历树
                int cmp = cpr.compare(k, p.key);//判断树的节点大小
                if (cmp < 0)
                    p = p.left;//左子树遍历
                else if (cmp > 0)
                    p = p.right;//右子树遍历
                else
                    return p;//返回数据
            }
        }
        return null;//返回null
    }

5 put方法

    public V put(K key, V value) {
        Entry<K,V> t = root;
        if (t == null) {//先判断根节点是否为null
            compare(key, key); // type (and possibly null) check

            root = new Entry<>(key, value, null);
            size = 1;  
            modCount++;//修改次数+1
            return null;//返回null
        }
        //存在根节点,树不为空 
        int cmp;
        Entry<K,V> parent;
        // split comparator and comparable paths
        Comparator<? super K> cpr = comparator;
        if (cpr != null) {//存在比较器
            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);//存放数据
            } while (t != null);
        }
        else {
            if (key == null)
                throw new NullPointerException();
            @SuppressWarnings("unchecked")
                Comparable<? super K> k = (Comparable<? super K>) key;
            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);
        }
        // 红黑树插入节点后,不再是一颗红黑树;
        // 这里通过fixAfterInsertion的处理,来恢复红黑树的特性
        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;
    }

6、remove方法

    public V remove(Object key) {//移除数据
        Entry<K,V> p = getEntry(key);//调用getEntry方法找到节点
        if (p == null)//判断节点如果不存在
            return null;//返回null

        V oldValue = p.value;//存在
        deleteEntry(p);
        return oldValue;//返回old数据
    }

6.1 deleteEntry方法

    private void deleteEntry(Entry<K,V> p) {
        modCount++;//修改次数+1
        size--;

        //如果删除有两个字节点,不能直接删除
              //要删除他的后继节点,后继节点最多只有一个子节点。 因为如果p有两个子节点,你删除之 
              //后他的两个子节点怎么挂载,挂载到p的父节点下?这显然不合理,因为这样一来p的父节点 
              //很有可能会有3个子节点,那么最好的办法就是找一个替罪羊,删除p的后继节点s,当然删 
              //除前需要把后继节点s的值赋给p
        if (p.left != null && p.right != null) {
            //successor返回p节点的后继节点,其实这个后继节点就是比p大的最小值,这个下面再分析
            Entry<K,V> s = successor(p);
            p.key = s.key;
            p.value = s.value;
            p = s;
        } // p has 2 children

       
        Entry<K,V> replacement = (p.left != null ? p.left : p.right);
        //如果删除节点有一个子节点
        if (replacement != null) {
            // Link replacement to parent
            replacement.parent = p.parent;
            if (p.parent == null)//删除的是root节点
                root = replacement;//直接把replacement作为root节点
            else if (p == p.parent.left) //替换p节点,左节点继续作为左节点
                p.parent.left  = replacement;
            else                         //替换p节点,右节点继续作为右节点
                p.parent.right = replacement;

            // Null out links so they are OK to use by fixAfterDeletion.
            p.left = p.right = p.parent = null;//都置空,利于GC回收

            // Fix replacement
            //如果删除的是黑色要进行调整,因为黑色删除会打破红黑平衡,
			//所以这里只是做颜色调整,调整的时候并没有删除。
            if (p.color == BLACK)
                fixAfterDeletion(replacement);
        } else if (p.parent == null) { // return if we are the only node.只存在root节点
            root = null;//直接置空删除
        } else { //  No children.没有子节点
            if (p.color == BLACK)//黑色会影响平衡
                fixAfterDeletion(p);

            if (p.parent != null) {//判断父节点是否存在
                if (p == p.parent.left)//把父节点的left置空
                    p.parent.left = null;
                else if (p == p.parent.right)//把父节点的right置空
                    p.parent.right = null;
                p.parent = null;
            }
        }
    }

6.2 successor方法

    static <K,V> TreeMap.Entry<K,V> successor(Entry<K,V> t) {
        if (t == null)
            return null;
        else if (t.right != null) { //右节点不为null
            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;
        }
    }

参考:TreeMap红黑树源码详解

猜你喜欢

转载自blog.csdn.net/MrLiar17/article/details/85053276
今日推荐