/**
* The backing map.
*/privatetransient NavigableMap<E,Object> m;
// Dummy value to associate with an Object in the backing Mapprivatestaticfinal Object PRESENT = new Object();
privatestaticfinallong serialVersionUID = -2479143000061671589L;
构造函数
/**
* Constructs a set backed by the specified navigable map.
*/
TreeSet(NavigableMap<E,Object> m) {
this.m = m;
}
/**
* Constructs a new, empty tree set, sorted according to the
* natural ordering of its elements.
*/publicTreeSet() {
this(new TreeMap<E,Object>());
}
/**
* Constructs a new, empty tree set, sorted according to the specified
* comparator.
*/publicTreeSet(Comparator<? super E> comparator) {
this(new TreeMap<>(comparator));
}
/**
* Constructs a new tree set containing the elements in the specified
* collection, sorted according to the <i>natural ordering</i> of its
* elements.
*/publicTreeSet(Collection<? extends E> c) {
this();
addAll(c);
}
/**
* Constructs a new tree set containing the same elements and
* using the same ordering as the specified sorted set.
*/publicTreeSet(SortedSet<E> s) {
this(s.comparator());
addAll(s);
}
常用方法
/**
* Returns the number of elements in this set (its cardinality).
*/publicintsize() {
return m.size();
}
/**
* Returns {@code true} if this set contains no elements.
*/publicbooleanisEmpty() {
return m.isEmpty();
}
/**
* Returns {@code true} if this set contains the specified element.
*/publicbooleancontains(Object o) {
return m.containsKey(o);
}
/**
* Adds the specified element to this set if it is not already present.
*/publicbooleanadd(E e) {
return m.put(e, PRESENT)==null;
}
/**
* Removes the specified element from this set if it is present.
*/publicbooleanremove(Object o) {
return m.remove(o)==PRESENT;
}
/**
* Removes all of the elements from this set.
* The set will be empty after this call returns.
*/publicvoidclear() {
m.clear();
}
/**
* Returns a shallow copy of this {@code TreeSet} instance. (The elements
* themselves are not cloned.)
*
* @return a shallow copy of this set
*/@SuppressWarnings("unchecked")
public Object clone() {
TreeSet<E> clone;
try {
clone = (TreeSet<E>) super.clone();
} catch (CloneNotSupportedException e) {
thrownew InternalError(e);
}
clone.m = new TreeMap<>(m);
return clone;
}