SortedSet
概述
A {@link Set} that further provides a total ordering on its elements. 提供 元素排序 的set;
The elements are ordered using their {@linkplain Comparable natural ordering}, or by a {@link Comparator} typically provided at sorted set creation time.
使用 元素的Comparable自然排序 或 创建set指定的Comparator 排序;
All elements inserted into a sorted set must implement the <tt>Comparable</tt> interface (or be accepted by the specified comparator).
被插入SortedSet的元素 必须实现Comparable 或 创建SortedSet指定comparator;
TreeSet
概述
A {@link NavigableSet} implementation based on a {@link TreeMap}. 基于TreeMap的Set实现;
The elements are ordered using their {@linkplain Comparable natural ordering}, or by a {@link Comparator} provided at set creation time, depending on which constructor is used.
TreeSet的元素 使用 元素的Comparable自然排序 或 创建TreeSet的Comparator排序;
This implementation provides guaranteed log(n) time cost for the basic operations ({@code add}, {@code remove} and {@code contains}).
add(), remove(), contains() 时间复杂度 log(n);
Note that this implementation is not synchronized.
TreeSet是非线程同步的;
If multiple threads access a tree set concurrently, and at least one of the threads modifies the set, it <i>must</i> be synchronized externally.
如果多个线程并发访问TreeSet,需要在外部进行同步操作;
If no such object exists, the set should be "wrapped" using the {@link Collections#synchronizedSortedSet} method.
可以使用 Collections#synchronizedSortedSet实现同步;
实现
public class TreeSet<E> extends AbstractSet<E> implements NavigableSet<E>, Cloneable, java.io.Serializable { private transient NavigableMap<E,Object> m; TreeSet(NavigableMap<E,Object> m) { this.m = m; } public TreeSet() { this(new TreeMap<E,Object>()); } public TreeSet(Comparator<? super E> comparator) { this(new TreeMap<>(comparator)); } public boolean add(E e) { return m.put(e, PRESENT)==null; } public boolean remove(Object o) { return m.remove(o)==PRESENT; } public boolean contains(Object o) { return m.containsKey(o); } ... }