TreeSet 源码分析

TreeSet

1)底层由 TreeMap 支持的 Set 接口实现,Set 中的元素按照自然顺序或指定的比较器排序。

创建实例

    /**
     *  支持此 Set 的底层的 TreeMap 对象
     */
    private transient NavigableMap<E,Object> m;

    // Dummy value to associate with an Object in the backing Map
    private static final Object PRESENT = new Object();

    TreeSet(NavigableMap<E,Object> m) {
        this.m = m;
    }

    /**
     *  构造一个新的空 set,该 set 根据其元素的自然顺序进行排序。
     */
    public TreeSet() {
        this(new TreeMap<>());
    }

    /**
     *  构造一个新的空 TreeSet,它根据指定比较器进行排序。
     */
    public TreeSet(Comparator<? super E> comparator) {
        this(new TreeMap<>(comparator));
    }

    /**
     *  构造一个包含指定 collection 中所有元素的新 TreeSet,它按照元素的自然顺序进行排序。
     */
    public TreeSet(Collection<? extends E> c) {
        this();
        addAll(c);
    }

    /**
     *  构造一个与指定 SortedSet 具有相同映射关系和比较器的新 TreeSet。
     */
    public TreeSet(SortedSet<E> s) {
        this(s.comparator());
        addAll(s);
    }

posted on 2018-11-29 23:10  竺旭东  阅读(69)  评论(0编辑  收藏  举报

导航