TreeMap 工作原理及实现

HashMap不保证数据有序
LinkedHashMap保证数据插入有序
要保证map的key可以大小排序,使用TreeMap集合

TreeMap<Integer, String> treeMap = new TreeMap<>();
        treeMap.put(4,"qd");
        treeMap.put(3,"sd");
        treeMap.put(1,"sd");
        treeMap.put(5,"sd");
        treeMap.put(7,"sd");
        treeMap.put(9,"sd");
        treeMap.put(0,"sd");
        for(Map.Entry<Integer,String> entry: treeMap.entrySet()){
            System.out.println(entry.getKey()+" "+entry.getValue());

        }

TreeMap如何实现有序遍历 treemap如何保证有序_TreeMap如何实现有序遍历


key是按照大小排序,
treeMap 能够按照key大小排序
key不能为null,key不能重复
如何做到数据有序的呢?红黑树
红黑树

红黑树(Red-Black Tree)首先是一颗二叉树,**二叉树的特征是树中的任何节点的值大于他的左孩子节点、**且小于它的右孩子节点,提高检索效率

二叉树在生成过程中容易失衡,导致检索效率降低

TreeMap如何实现有序遍历 treemap如何保证有序_子节点_02

平衡二叉树:是一颗空树或左右子树的高度差的绝对值不超过1,并且左右孩子都是一颗平衡二叉树,

TreeMap如何实现有序遍历 treemap如何保证有序_子节点_03

红黑树是一种平衡的二叉树,要保证数据的平衡,二叉树是要满足以下特点:

1、每个节点都只能是红色或者黑色

2、根节点必须是黑色

3、每个叶子节点是黑色的

4、如果一个节点是红色的,则它的子节点都是黑色的,一条路径上不能出现相邻的两个红色节点

5、从任意一个节点到其叶子节点包含相同数目的黑色节点

TreeMap如何实现有序遍历 treemap如何保证有序_子节点_04

插入后者删除数据,红黑树就发生了变换,调整无非左旋、右旋、或者着色

TreeMap如何实现有序遍历 treemap如何保证有序_二叉树_05


TreeMap如何实现有序遍历 treemap如何保证有序_子节点_06

复杂难点在于旋转和着色的过程
TreeMap
存储数据在Entry节点中,entry定义如下:

static final class Entry<K,V> implements Map.Entry<K,V> {
        K key; //键
        V value; //值
        Entry<K,V> left = null;//左孩子
        Entry<K,V> right = null;//右孩子
        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;
        }
private final Comparator<? super K> comparator;//比较器
    private transient Entry<K,V> root = null; //root属性,红黑树的根节点,是entry类型
entry节点根据key进行排序

    /**
     * The number of entries in the tree
     */
    private transient int size = 0;  //存储数据数量
//默认的构造方法,comparator为null,按照key自然顺序来位置TreeMap的顺序
public TreeMap() {
        comparator = null;
    }

//指定一个比较器来构造一个TreeMap
public TreeMap(Comparator<? super K> comparator) {
        this.comparator = comparator;
    }


//
    public TreeMap(Map<? extends K, ? extends V> m) {
        comparator = null;
        putAll(m);
    }


//构造一个sortmap的TreeMap,使用sortmap实例的构造器来实例TreeMap
    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) {
        }
    }

构造函数

TreeMap如何实现有序遍历 treemap如何保证有序_二叉树_07


treemap提供的api

TreeMap如何实现有序遍历 treemap如何保证有序_子节点_08


TreeMap如何实现有序遍历 treemap如何保证有序_红黑树_09