从新认识TreeMap

特色

TreeMap类不只实现了Map接口,还实现了Map接口的子接口java.util.SortedMap。由TreeMap类实现的Map集合,不容许键对象为nulljava

核心

  1. 红黑树
  2. 比较器实现大小比较。

红黑树

一种平衡二叉树的实现。数据结构

比较器

因为TreeMap须要排序,因此须要一个Comparator为键值进行大小比较.固然也是用Comparator定位的.code

  1. Comparator能够在建立TreeMap时指定
  2. 若是建立时没有肯定,那么就会使用key.compareTo()方法,这就要求key必须实现Comparable接口.
  3. TreeMap是使用Tree数据结构实现的,因此使用compare接口就能够完成定位了.

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

从put方法可看出,若是构造TreeMap指定了Comparator,使用Comparator做为比较依据;不然利用key实现的Comparable接口做为比较大小依据。排序

问题

  1. 前面提到,HashMap的key无需,可是添加查找删除操做的时间复杂度都接近于O(1),LinkedHashMap的添加删除查找的时间复杂度也接近于O(1),并且按key能够有两种有序(按插入,按访问),那为何还须要一种时间复杂度为O(logn)的按key有序的数据结构? TreeMap默认是按键值的升序排序,也能够指定排序的比较器(比较可定制),当用Iterator 遍历TreeMap时,获得的记录是排过序的。接口

  2. TreeMap便可经过构造时指定comparator进行排序,也可按照key实现的comparable接口排序,那么都实现了,而且排序规则不一样,默认使用哪一种?默认优先使用构造时传入的Comparator,而后才会使用key实现的comparable接口。get

  3. 通常在须要按天然排序或者按指定方式排序输出使用TreeMap;按输入顺序输出,则使用LinkedHashMapit

Thanks for reading! want moreio

相关文章
相关标签/搜索