TreeMap源码分析

来源:互联网 发布:wlk数据库 编辑:程序博客网 时间:2024/06/11 08:16

前言

为了看TreeMap的源码我把算法4和算法导论红黑树的章节是撸了一遍又一遍,终于大概了解红黑树的工作机制,红黑树是由2-3二叉搜索树转变而来也可以说红黑树是2-3二叉搜索树的一种实现,他是一种平衡二叉搜索树,他具有以下五条性质:

  • 每个结点不是红色就是黑色
  • 根结点是黑色
  • 每个叶结点是黑色
  • 如果一个结点是红色,那么它的两个子结点都是黑色
  • 对于每个结点,从该结点到其所有后代叶子结点的简单路径上,均包含相同个数的黑色结点。

    根据这五条性质决定了红黑树的树高不超过lgn,也就是所有操作的时间复杂度不超过O(lgn)。

但是说实话目前为止,红黑树删除操作后整理结点颜色的四种情况还是有些云里雾里,但是已经不影响看TreeMap的源码了。

官方解释

我们先来看TreeMap的官方解释:
基于红黑树(Red-Black tree)的 NavigableMap 实现。该映射根据其键的自然顺序进行排序,或者根据创建映射时提供的 Comparator 进行排序,具体取决于使用的构造方法。
注意,此实现不是同步的。如果多个线程同时访问一个映射,并且其中至少一个线程从结构上修改了该映射,则其必须 外部同步。

TreeMap定义

public class TreeMap<K,V>    extends AbstractMap<K,V>    implements NavigableMap<K,V>, Cloneable, java.io.Serializable

成员变量

 //用于接收传进来的比较器 private final Comparator<? super K> comparator; //红黑树的根节点 private transient Entry<K,V> root; //树中结点的个数 private transient int size = 0; //用于记录改变树结构的次数 private transient int modCount = 0;

构造函数

   //无参构函,如果没有传入比较器,那么就使用默认的比较方法    public TreeMap() {        comparator = null;    }    //接收传进来的比较器的构函    public TreeMap(Comparator<? super K> comparator) {        this.comparator = comparator;    }    //结构参数为Map的构造器,使用默认的比较方法,用传进来的Map来填充树    public TreeMap(Map<? extends K, ? extends V> m) {        comparator = null;        putAll(m);//函数内部先检查Map是否为有序Map。如果是,将比较器赋值,并调用put方法填充树    }   //使用有序Map填充树,首先把参数的比较器赋值给当前比较器变量。    public TreeMap(SortedMap<K, ? extends V> m) {        comparator = m.comparator();        try {            buildFromSorted(m.size(), m.entrySet().iterator(), null, null);        } catch (java.io.IOException cannotHappen) {        } catch (ClassNotFoundException cannotHappen) {        }    }

内部类

//这个静态内部类就是定义树结点的类。    static final class Entry<K,V> implements Map.Entry<K,V> {        K key;//结点键        V value;//结点值        Entry<K,V> left;//结点的左子树        Entry<K,V> right;//结点的右子树        Entry<K,V> parent;//结点的父结点        boolean color = BLACK;//结点的颜色        /**         * Make a new cell with given key, value, and parent, and with         * {@code null} child links, and BLACK color.         */        Entry(K key, V value, Entry<K,V> parent) {            this.key = key;            this.value = value;            this.parent = parent;        }        public K getKey() {            return key;        }        public V getValue() {            return value;        }        public V setValue(V value) {            V oldValue = this.value;            this.value = value;            return oldValue;        }        public boolean equals(Object o) {            if (!(o instanceof Map.Entry))                return false;            Map.Entry<?,?> e = (Map.Entry<?,?>)o;            return valEquals(key,e.getKey()) && valEquals(value,e.getValue());        }        public int hashCode() {            int keyHash = (key==null ? 0 : key.hashCode());            int valueHash = (value==null ? 0 : value.hashCode());            return keyHash ^ valueHash;        }        public String toString() {            return key + "=" + value;        }    }

核心成员方法

我们先来看构建红黑树的核心方法。

前驱后继

   //寻找指定结点的后继结点,也就是比指定结点大的最小结点。这个方法的使用和二叉搜索树的方法完全一致   static <K,V> TreeMap.Entry<K,V> successor(Entry<K,V> t) {        if (t == null)            return null;        else if (t.right != 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;        }    }
//寻找指定结点的前驱结点。比指定结点小的最大结点 static <K,V> Entry<K,V> predecessor(Entry<K,V> t) {        if (t == null)            return null;        else if (t.left != null) {            Entry<K,V> p = t.left;            while (p.right != null)                p = p.right;            return p;        } else {            Entry<K,V> p = t.parent;            Entry<K,V> ch = t;            while (p != null && ch == p.left) {                ch = p;                p = p.parent;            }            return p;        }    }

返回属性

//返回当前结点的颜色 private static <K,V> boolean colorOf(Entry<K,V> p) {        return (p == null ? BLACK : p.color);    }//返回当前结点的父结点    private static <K,V> Entry<K,V> parentOf(Entry<K,V> p) {        return (p == null ? null: p.parent);    }//给当前结点设置颜色    private static <K,V> void setColor(Entry<K,V> p, boolean c) {        if (p != null)            p.color = c;    }  //返回当前结点的左子树    private static <K,V> Entry<K,V> leftOf(Entry<K,V> p) {        return (p == null) ? null: p.left;    }//返回当前结点的右子树    private static <K,V> Entry<K,V> rightOf(Entry<K,V> p) {        return (p == null) ? null: p.right;    }

左旋右旋

//左旋转树,旋转不破坏红黑树的基本性质,基本思想是,以指定结点为根的子树向左旋转,旋转后指定结点的右子树为子树的根,指定结点的右子树的左子树作为指定结点的右子树,其他不变。下面有示意图。 private void rotateLeft(Entry<K,V> p) {        if (p != null) {            Entry<K,V> r = p.right;            p.right = r.left;            if (r.left != null)                r.left.parent = p;            r.parent = p.parent;            if (p.parent == null)                root = r;            else if (p.parent.left == p)                p.parent.left = r;            else                p.parent.right = r;            r.left = p;            p.parent = r;        }    }

这里写图片描述

右旋就是左旋的逆操作,以下是右旋的代码:

 private void rotateRight(Entry<K,V> p) {        if (p != null) {            Entry<K,V> l = p.left;            p.left = l.right;            if (l.right != null) l.right.parent = p;            l.parent = p.parent;            if (p.parent == null)                root = l;            else if (p.parent.right == p)                p.parent.right = l;            else p.parent.left = l;            l.right = p;            p.parent = l;        }    }

左旋和右旋的作用就是通过旋转不破坏红黑树的性质,用来对插入和删除红黑树结点时对红黑树性质的破坏进行修复。

插入操作

//插入后可能会破坏红黑树的性质,下面函数就是用来修复这种破坏影响,使插入后依然保持红黑树的性质吗,具体的分析请看算法导论和算法4红黑树部分private void fixAfterInsertion(Entry<K,V> x) {        x.color = RED;        while (x != null && x != root && 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))) {                        x = parentOf(x);                        rotateLeft(x);                    }                    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;    }

删除操作

//从红黑树删除指定结点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);        if (replacement != null) {            // Link replacement to parent            replacement.parent = p.parent;            if (p.parent == null)                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)                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.            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;            }        }    }
//用于删除后,对红黑树性质恢复的方法。 private void fixAfterDeletion(Entry<K,V> x) {        while (x != root && colorOf(x) == BLACK) {            if (x == leftOf(parentOf(x))) {                Entry<K,V> sib = rightOf(parentOf(x));                if (colorOf(sib) == RED) {                    setColor(sib, BLACK);                    setColor(parentOf(x), RED);                    rotateLeft(parentOf(x));                    sib = rightOf(parentOf(x));                }                if (colorOf(leftOf(sib))  == BLACK &&                    colorOf(rightOf(sib)) == BLACK) {                    setColor(sib, RED);                    x = parentOf(x);                } else {                    if (colorOf(rightOf(sib)) == BLACK) {                        setColor(leftOf(sib), BLACK);                        setColor(sib, RED);                        rotateRight(sib);                        sib = rightOf(parentOf(x));                    }                    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);    }

添加操作

//向树中添加元素,由于是对红黑树进行添加操作,格外的麻烦啊,我们可以看到最后还得调用fixAfterInsertion方法对添加后的红黑树进行性质的恢复。  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;        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);        }        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;    }

移出操作

  public V remove(Object key) {        Entry<K,V> p = getEntry(key);//想把对应key的结点查出来        if (p == null)            return null;        V oldValue = p.value;        deleteEntry(p);//进行删除操作        return oldValue;    }

总结:以上就是TreeMap的核心的源码实现,掌握这些核心的源码再看其他的方法问题应该就不大了,在这里红黑树至少对于我来说是一个难点,后续我也许会对红黑树的做一个详细分析,红黑树的难点在于删除操作的情况较为复杂,红黑树的性能还是相当不错的,以至于现在很对应用都采用了红黑树的数据结构。

原创粉丝点击