前言
TreeSet集合底层数据结构采用红黑树实现,元素唯一且已经排好序。
TreeSet集合继承了AbstractSet类,实现了NavigableSet接口。其框架图如下:
蓝色代表接口,黑体代表类。
一、TreeSet集合初始化
- TreeSet():无参构造,初始容量为0。源码如下:
/**
* Constructs a new, empty tree set, sorted according to the
* natural ordering of its elements. All elements inserted into
* the set must implement the {@link Comparable} interface.
* Furthermore, all such elements must be <i>mutually
* comparable</i>: {@code e1.compareTo(e2)} must not throw a
* {@code ClassCastException} for any elements {@code e1} and
* {@code e2} in the set. If the user attempts to add an element
* to the set that violates this constraint (for example, the user
* attempts to add a string element to a set whose elements are
* integers), the {@code add} call will throw a
* {@code ClassCastException}.
*/
public TreeSet() {
this(new TreeMap<E,Object>());
}
该构造函数调用了TreeSet集合中的另一个有参构造,其参数可以是NavigableMap接口的任何实现类。
- TreeSet(NavigableMap<E,Object> m):有参构造,参数是NavigableMap接口的实现类。源码如下:
/**
* Constructs a set backed by the specified navigable map.
*/
TreeSet(NavigableMap<E,Object> m) {
this.m = m;
}
初始化本集合中的m变量,那m变量是啥呢?源码如下:
/**
* The backing map.
*/
private transient NavigableMap<E,Object> m;
该m变量是NavigableMap类型。所以,通过这两个构造函数可以看出TreeSet集合底层就是NavigableMap的各种实现类。
- TreeSet(Collection<? extends E> c):有参构造,参数可以是List、Set接口的所有实现类。源码如下:
/**
* Constructs a new tree set containing the elements in the specified
* collection, sorted according to the <i>natural ordering</i> of its
* elements. All elements inserted into the set must implement the
* {@link Comparable} interface. Furthermore, all such elements must be
* <i>mutually comparable</i>: {@code e1.compareTo(e2)} must not throw a
* {@code ClassCastException} for any elements {@code e1} and
* {@code e2} in the set.
*
* @param c collection whose elements will comprise the new set
* @throws ClassCastException if the elements in {@code c} are
* not {@link Comparable}, or are not mutually comparable
* @throws NullPointerException if the specified collection is null
*/
public TreeSet(Collection<? extends E>