JDK 1.8 TreeMap源码分析

/**
     * TreeMap特点:
     *  底层:二叉红黑树 key输入无序,升序排列,null不可以
     *  1.2
     */
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;
    //内部结构
        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;//颜色
        }
        
        //key 为基础类型,当为自定义的时候需要实现Comparator接口
            public TreeMap() {
        comparator = null;
    }
    //key 为自定义引用类型,当为自定义的时候需要实现Comparator接口
    public TreeMap(Comparator<? super K> comparator) {
        this.comparator = comparator;
    }
    
    public V put(K key, V value) {
        Entry<K,V> t = root;
        //如果root为null,则直接设置为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 {
            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;
    }
}
posted @ 2023-01-18 17:23  李悠然  阅读(16)  评论(0编辑  收藏  举报