TreeSet
基于TreeMap实现的树集
目录
TreeSet继承关系
TreeSet实现了Serializable接口,支持序列化,可通过序列化传输
TreeSet实现了Cloneable接口,覆盖了clone()方法,能被克隆
TreeSet实现了NavigableSet接口,可以元素匹配,升/降序访问和遍历元素,返回集的视图
TreeSet实现了List接口和继承了Abstractlist抽象类,可进行集合相关的操作
TreeSet源码分析
TreeSet构造函数:
/**
* 构造一个由指定的NavigableMap支持的集
*/
TreeSet(NavigableMap<E,Object> m) {
this.m = m;
}
/**
* 构造一个树集, 并根据其元素的自然顺序排序, 集中的所有元素都须实现 Comparable 接口
* 所有元素都必须相互可比, 否则方法将抛出ClassCastException异常
*/
public TreeSet() {
this(new TreeMap<>());
}
/**
* 构造一个新树集, 根据指定的比较器排序
* 集中的所有元素必须与指定的比较器相互比较, 否则方法将抛出ClassCastException异常
*
* @param comparator the comparator that will be used to order this set.
* If {@code null}, the {@linkplain Comparable natural
* ordering} of the elements will be used.
*/
public TreeSet(Comparator<? super E> comparator) {
this(new TreeMap<>(comparator));
}
/**
* 构造一个包含指定集合中元素的新树集, 根据元素的自然顺序排序
* 插入集中的所有元素必须实现Comparable接口, 所有元素都必须相互可比
*
* @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> c) {
this();
addAll(c);
}
/**
* 构造一个新的树集, 与指定排序集有 相同元素 和 同一顺序
*
* @param s sorted set whose elements will comprise the new set
* @throws NullPointerException if the specified sorted set is null
*/
public TreeSet(SortedSet<E> s) {
this(s.comparator());
addAll(s);
}
TreeSet迭代器相关方法:
/**
* 升序方式返回元素迭代器
*
* @return an iterator over the elements in this set in ascending order
*/
public Iterator<E> iterator() {
return m.navigableKeySet().iterator();
}
/**
* 降序方式返回元素迭代器
*
* @return an iterator over the elements in this set in descending order
* @since 1.6
*/
public Iterator<E&