Java集合 TreeMap 源码浅析

TreeMap 是如何排序的? 是对 key 排序还是对什么排序?

官方描述:

/**
* A Red-Black tree based {@link NavigableMap} implementation.
* The map is sorted according to the {@linkplain Comparable natural
* ordering} of its keys, or by a {@link Comparator} provided at map
* creation time, depending on which constructor is used.
* /

清晰的说到, 是对 key 进行自然排序, 底层数据结构为红黑树, 即一颗 二叉 排序树.


具体是使用 key 的 compareable 进行内部排序还是使用 comparator 进行外部排序是根据使用了那个构造方法来决定的.


TreeMap 的底层数据结构是什么?

 /**
     * Node in the Tree.  Doubles as a means to pass key-value pairs back to
     * user (see Map.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;  // ------- 1

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

从 TreeMap 的官方描述和源码中看到, TreeMap 底层就是使用 红黑树来实现的, 没有用到 HashMap 散列机制, 所以 get 速度自然就没有 HashMap 快.
因此只有当我们需要按照自然排序的顺序去遍历 map 中的键值对时才考虑使用 TreeMap.



TreeMap 的实现比 HashMap 要简单很多, 因为没有使用到 hash 机制, 因此也不涉及什么 hash 冲突的维持, 扩容机制, 负载因子等等, 只需要在插入或删除元素的时候维持好红黑树的结构即可.

你可能感兴趣的:(集合)