TreeMap 源码分析

一、类图

       

二、源码分析

       a.  基于红黑树实现,使用 key 排序,Key 需要实现 Comparable 接口,或者创建时传入 Comparator

       b.  log(n) 时间复杂度

       c.  原则上,Comparable / Comparator 处理相等应该与 equals 保持一致,否则就违背了 Map 的接口定义

            但,TreeMap 查找 key 不再依赖 equals,而是直接基于 Comparable / Comparator,违背了也能正常工作

      d.  iterator 是 Fail-fast 的,遍历时被修改,会抛出 ConcurrentModificationException

       f.  实现了序列化和克隆接口

       g.  putAll(Map m) 花费 n*log(n) 时间,使用 SortedMap 拷贝构造,花费线性时间

       h.  containsValue 花费线性时间(与 size 有关)

        i.  jdk 1.8 的集合都添加了并行(可分割)迭代器 Spliterator,采用了函数式编程框架,例如

        public boolean tryAdvance(Consumer<? super K> action) {
            TreeMap.Entry<K,V> e;
            if (action == null)
                throw new NullPointerException();
            if (est < 0)
                getEstimate(); // force initialization
            if ((e = current) == null || e == fence)
                return false;
            current = successor(e);
            action.accept(e.key);
            if (tree.modCount != expectedModCount)
                throw new ConcurrentModificationException();
            return true;
        }

// 只需要告诉你想如何处理集合元素(action),程序会自动并行化迭代

           现在的三种 Set View 都支持两种 iterator,一种普通的 iterator ,另一种就是 spliterator

           这些 spliterator 都是静态内部类实现的,各种 Set View 也是静态内部类,普通 Set View iterator 是内部类

   class Values extends AbstractCollection<V> {
        public Iterator<V> iterator() {
            return new ValueIterator(getFirstEntry());
        }

        public int size() {
            return TreeMap.this.size();
        }

        public boolean contains(Object o) {
            return TreeMap.this.containsValue(o);
        }

        public boolean remove(Object o) {
            for (Entry<K,V> e = getFirstEntry(); e != null; e = successor(e)) {
                if (valEquals(e.getValue(), o)) {
                    deleteEntry(e);
                    return true;
                }
            }
            return false;
        }

        public void clear() {
            TreeMap.this.clear();
        }

        public Spliterator<V> spliterator() {
            return new ValueSpliterator<K,V>(TreeMap.this, null, null, 0, -1, 0);
        }

    }

     j.   Entry 包含 key value left right parent color,红黑树节点

          

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值