TreeSet源码分析

源码来自jdk1.8


  • 实现了NavigableSet接口
  • 内部实现依赖于TreeMap
  • add, remove, contains use log(n) time
  • 不允许null值(Comparable/Comparator)
  • 不同步
  • iterator fast fail
public class TreeSet extends AbstractSet
    implements NavigableSet, Cloneable, java.io.Serializable
{
    /**
     * The backing map.
     */
    private transient NavigableMap m;

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

    /**
     * Constructs a set backed by the specified navigable map.
     */
    TreeSet(NavigableMap m) {
        this.m = m;
    }

    /**
     * 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 mutually
     * comparable: {@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());
    }

    /**
     * Constructs a new, empty tree set, sorted according to the specified
     * comparator.  All elements inserted into the set must be mutually
     * comparable by the specified comparator: {@code comparator.compare(e1,
     * 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, the
     * {@code add} call will throw a {@code 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 comparator) {
        this(new TreeMap<>(comparator));
    }
    // 省略了其他方法
}

基本与HashSet类似,value存为PRESENT,方法都是调用TreeMap的方法实现的。

你可能感兴趣的:(TreeSet源码分析)