TreeMap源码分析

TreeSet、TreeMap

概述

与HashSet及HashMap类似,TreeSet是基于TreeMap实现的,所以分析TreeMap即可。
TreeMap是基于红黑树实现的,元素是根据key的自然顺序排列的,也可以在构造器中传入Comarator来指定排序器。
containsKey、get、put、remove操作都是log(n)时间复杂度的,要注意排序的规则要与key的equals一致,也就是如果compareTo为0时,equals也应该返回true。这是因为Map是根据equals来定义的,而treemap又是根据comparable来排序的,如果两者不一致,则违背了Map的协议。
由于TreeMap的key是根据comparable的compareTo来排序的,所以应该实现这个接口,否则会出错。
这两个类是非同步的,迭代机制是fail-fast的。

源码分析

  • 构造器
    // 构建一个空的TreeMap,元素按照key的自然顺序来排序,即compareTo的返回值。
    public TreeMap() {
        comparator = null;
    }
    // 可以传入一个comparator
    public TreeMap(Comparator<? super K> comparator) {
        this.comparator = comparator;
    }
    // 可以传入一个Map,会将该map的所有元素添加进去
    public TreeMap(Map<? extends K, ? extends V> m) {
        comparator = null;
        putAll(m);
    }
    // 如果原来的map是有序的,会由buildFromSorted方法来构建,该方法是递归构造树的方法
    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) {
        }
    }
  • put
    // 添加新的键值对,如果key已经存在,则进行更新
    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) {
            // 如果设定了comparator,则按其排序,否则将key转化为comparable通过compareTo来排序
            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的逻辑比较简单,就是根据comparable或者comparator来找到对应的节点,主要就是排序二叉树的查找;找到节点后设置一下,再根据需要调整红黑树,红黑树的具体算法就不深入看了,很多算法书都提及到,一般知道大概原理就行了。

  • 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) {
        // Offload comparator-based version for sake of performance
        if (comparator != null)
            // 使用comparator来查找
            return getEntryUsingComparator(key);
        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;
    }

get方法也没什么特别的,就是简单的排序二叉树的查找过程。这个类里可以看到不少地方都有重复的逻辑,比如二叉树的元素查找。由于Java没有内联方法,为了提高运行效率,所以冗余度较高。

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

总结

如果不深入研究红黑树的话,其实TreeMap是比较简单的,只涉及到二叉树查找过程。使用时注意comparable和comparator的存在,明白排序的依据,注意作为key的类的相关方法即可。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值