Java集合之TreeSet

来源:互联网 发布:淘宝美工工资待遇知乎 编辑:程序博客网 时间:2024/05/21 13:54

TreeSet继承AbstractSet,AbstractSet继承AbstractCollection并且实现了Set接口,它的底层是NavigableMap。

构造方法

1. 无参构造

public TreeSet() {        this(new TreeMap<E,Object>());}

隐式调用带参构造。

2. 带参构造

TreeSet(NavigableMap<E,Object> m) {        this.m = m;}public TreeSet(Comparator<? super E> comparator) {        this(new TreeMap<>(comparator));}public TreeSet(Collection<? extends E> c) {        this();        addAll(c);}public TreeSet(SortedSet<E> s) {        this(s.comparator());        addAll(s);}

没什么好说的,就是给底层的NavigableMap赋值。

常用方法

1. size()

public int size() {        return m.size();}

返回底层map的大小。

2. contains(Object o)

public boolean contains(Object o) {        return m.containsKey(o);}

调用map的containsKey方法。

3. add(E e)

private static final Object PRESENT = new Object();public boolean add(E e) {        return m.put(e, PRESENT)==null;}

调用map的put方法,e为key,PRESENT为value。

4. subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive)

public NavigableSet<E> subSet(E fromElement, boolean fromInclusive,                                  E toElement,   boolean toInclusive) {        return new TreeSet<>(m.subMap(fromElement, fromInclusive,                                       toElement,   toInclusive));}

获取一个子TreeSet,可以自定义是否包含头尾两个元素,除此之外,它还提供了headSet/tailSet方法。

5. first()

public E first() {        return m.firstKey();}

调用map的firstKey方法。

其实这样看下来,这个TreeSet类,基本都是在调用底层NavigableMap的一些方法来完成自己的工作,我觉得这个和HashSet的区别应该重点在与HashMap和NavigableMap的区别

0 0