TreeMap源码分析

==重点: Key对象只有实现了Comparable接口,数据结构才是有序的,java 的默认数据类型都有实现,自己定义的数据类型,请实现这个接口==


数据结构

采用红黑树的数据结构,具体的数据结构描述可以看这里

image

继承

  • 最小化实现接口AbstractMap
  • NavigableMap有序Map接口
  • Cloneable可复制的接口
  • Serializable可序列化接口
public class TreeMap<K,V>
    extends AbstractMap<K,V>
    implements NavigableMap<K,V>, Cloneable, java.io.Serializable
{}

构造

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;
    
    
    //无参数创建,在不提供比较器的情况下,采用Key对象的默认compareTo方法来比较节点大小
    public TreeMap() {
        comparator = null;
    }

    //通过比较器创建构建
    public TreeMap(Comparator<? super K> comparator) {
        this.comparator = comparator;
    }

    //通过其他map数据结构创建新数据
    public TreeMap(Map<? extends K, ? extends V> m) {
        comparator = null;
        putAll(m);
    }

    //提供有序的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) {
        }
    }
    
}

Entry 节点

由于采用的红黑树结构,它的节点自然也是符合左右子节点引用,父节点引用和节点颜色的特点,成员方法也是简单的常规方法

    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;
        }

        /**
         * Returns the key.
         *
         * @return the key
         */
        public K getKey() {
            return key;
        }

        /**
         * Returns the value associated with the key.
         *
         * @return the value associated with the key
         */
        public V getValue() {
            return value;
        }

        /**
         * Replaces the value currently associated with the key with the given
         * value.
         *
         * @return the value associated with the key before this method was
         *         called
         */
        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;
        }
    }

红黑树的自我调整

很绕,不要纠结,能看懂就看懂,看不懂,不要牛角尖,知道原理就行了

    /** From CLR */
    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;
    }

put

    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;
        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 {
            //非根节点的时候,是不允许key值是null
            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;
    }

get

基本就是二叉查找的过程,

    public V get(Object key) {
        Entry<K,V> p = getEntry(key);
        return (p==null ? null : p.value);
    }
    
    final Entry<K,V> getEntry(Object key) {
        //看一下是否要使用默认比较器
        if (comparator != null)
            return getEntryUsingComparator(key);
            
        //如果没有自定义比较器,使用NULL查找是会报错的
        if (key == null)
            throw new NullPointerException();
        @SuppressWarnings("unchecked")
            Comparable<? super K> k = (Comparable<? super K>) 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;
        }
        return null;
    }
    
    //这个是使用默认比较器查找的方式
    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;
    }

remove

    public V remove(Object key) {
        //先获取节点
        Entry<K,V> p = getEntry(key);
        if (p == null)
            return null;

        V oldValue = p.value;
        
        //删除节点
        deleteEntry(p);
        return oldValue;
    }
    
    private void deleteEntry(Entry<K,V> p) {
        modCount++;
        size--;

        //如果两个子节点都不为空,调整一下两个子节点
        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) { //根节点
            root = null;
        } else { //如果两个节点都没有
        
            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;
            }
        }
    }
    
  //将两个子节点调整成一颗树 
   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;
        }
    }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容