1. /*
  2. * @(#)TreeSet.java 1.32 03/12/19
  3. *
  4. * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
  5. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  6. */
  7. package java.util;
  8. /**
  9. * This class implements the <tt>Set</tt> interface, backed by a
  10. * <tt>TreeMap</tt> instance. This class guarantees that the sorted set will
  11. * be in ascending element order, sorted according to the <i>natural order</i>
  12. * of the elements (see <tt>Comparable</tt>), or by the comparator provided at
  13. * set creation time, depending on which constructor is used.<p>
  14. *
  15. * This implementation provides guaranteed log(n) time cost for the basic
  16. * operations (<tt>add</tt>, <tt>remove</tt> and <tt>contains</tt>).<p>
  17. *
  18. * Note that the ordering maintained by a set (whether or not an explicit
  19. * comparator is provided) must be <i>consistent with equals</i> if it is to
  20. * correctly implement the <tt>Set</tt> interface. (See <tt>Comparable</tt>
  21. * or <tt>Comparator</tt> for a precise definition of <i>consistent with
  22. * equals</i>.) This is so because the <tt>Set</tt> interface is defined in
  23. * terms of the <tt>equals</tt> operation, but a <tt>TreeSet</tt> instance
  24. * performs all key comparisons using its <tt>compareTo</tt> (or
  25. * <tt>compare</tt>) method, so two keys that are deemed equal by this method
  26. * are, from the standpoint of the set, equal. The behavior of a set
  27. * <i>is</i> well-defined even if its ordering is inconsistent with equals; it
  28. * just fails to obey the general contract of the <tt>Set</tt> interface.<p>
  29. *
  30. * <b>Note that this implementation is not synchronized.</b> If multiple
  31. * threads access a set concurrently, and at least one of the threads modifies
  32. * the set, it <i>must</i> be synchronized externally. This is typically
  33. * accomplished by synchronizing on some object that naturally encapsulates
  34. * the set. If no such object exists, the set should be "wrapped" using the
  35. * <tt>Collections.synchronizedSet</tt> method. This is best done at creation
  36. * time, to prevent accidental unsynchronized access to the set: <pre>
  37. * SortedSet s = Collections.synchronizedSortedSet(new TreeSet(...));
  38. * </pre><p>
  39. *
  40. * The Iterators returned by this class's <tt>iterator</tt> method are
  41. * <i>fail-fast</i>: if the set is modified at any time after the iterator is
  42. * created, in any way except through the iterator's own <tt>remove</tt>
  43. * method, the iterator will throw a <tt>ConcurrentModificationException</tt>.
  44. * Thus, in the face of concurrent modification, the iterator fails quickly
  45. * and cleanly, rather than risking arbitrary, non-deterministic behavior at
  46. * an undetermined time in the future.
  47. *
  48. * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
  49. * as it is, generally speaking, impossible to make any hard guarantees in the
  50. * presence of unsynchronized concurrent modification. Fail-fast iterators
  51. * throw <tt>ConcurrentModificationException</tt> on a best-effort basis.
  52. * Therefore, it would be wrong to write a program that depended on this
  53. * exception for its correctness: <i>the fail-fast behavior of iterators
  54. * should be used only to detect bugs.</i><p>
  55. *
  56. * This class is a member of the
  57. * <a href="{@docRoot}/../guide/collections/index.html">
  58. * Java Collections Framework</a>.
  59. *
  60. * @author Josh Bloch
  61. * @version 1.32, 12/19/03
  62. * @see Collection
  63. * @see Set
  64. * @see HashSet
  65. * @see Comparable
  66. * @see Comparator
  67. * @see Collections#synchronizedSortedSet(SortedSet)
  68. * @see TreeMap
  69. * @since 1.2
  70. */
  71. public class TreeSet<E>
  72. extends AbstractSet<E>
  73. implements SortedSet<E>, Cloneable, java.io.Serializable
  74. {
  75. private transient SortedMap<E,Object> m; // The backing Map
  76. private transient Set<E> keySet; // The keySet view of the backing Map
  77. // Dummy value to associate with an Object in the backing Map
  78. private static final Object PRESENT = new Object();
  79. /**
  80. * Constructs a set backed by the specified sorted map.
  81. */
  82. private TreeSet(SortedMap<E,Object> m) {
  83. this.m = m;
  84. keySet = m.keySet();
  85. }
  86. /**
  87. * Constructs a new, empty set, sorted according to the elements' natural
  88. * order. All elements inserted into the set must implement the
  89. * <tt>Comparable</tt> interface. Furthermore, all such elements must be
  90. * <i>mutually comparable</i>: <tt>e1.compareTo(e2)</tt> must not throw a
  91. * <tt>ClassCastException</tt> for any elements <tt>e1</tt> and
  92. * <tt>e2</tt> in the set. If the user attempts to add an element to the
  93. * set that violates this constraint (for example, the user attempts to
  94. * add a string element to a set whose elements are integers), the
  95. * <tt>add(Object)</tt> call will throw a <tt>ClassCastException</tt>.
  96. *
  97. * @see Comparable
  98. */
  99. public TreeSet() {
  100. this(new TreeMap<E,Object>());
  101. }
  102. /**
  103. * Constructs a new, empty set, sorted according to the specified
  104. * comparator. All elements inserted into the set must be <i>mutually
  105. * comparable</i> by the specified comparator: <tt>comparator.compare(e1,
  106. * e2)</tt> must not throw a <tt>ClassCastException</tt> for any elements
  107. * <tt>e1</tt> and <tt>e2</tt> in the set. If the user attempts to add
  108. * an element to the set that violates this constraint, the
  109. * <tt>add(Object)</tt> call will throw a <tt>ClassCastException</tt>.
  110. *
  111. * @param c the comparator that will be used to sort this set. A
  112. * <tt>null</tt> value indicates that the elements' <i>natural
  113. * ordering</i> should be used.
  114. */
  115. public TreeSet(Comparator<? super E> c) {
  116. this(new TreeMap<E,Object>(c));
  117. }
  118. /**
  119. * Constructs a new set containing the elements in the specified
  120. * collection, sorted according to the elements' <i>natural order</i>.
  121. * All keys inserted into the set must implement the <tt>Comparable</tt>
  122. * interface. Furthermore, all such keys must be <i>mutually
  123. * comparable</i>: <tt>k1.compareTo(k2)</tt> must not throw a
  124. * <tt>ClassCastException</tt> for any elements <tt>k1</tt> and
  125. * <tt>k2</tt> in the set.
  126. *
  127. * @param c The elements that will comprise the new set.
  128. *
  129. * @throws ClassCastException if the keys in the specified collection are
  130. * not comparable, or are not mutually comparable.
  131. * @throws NullPointerException if the specified collection is null.
  132. */
  133. public TreeSet(Collection<? extends E> c) {
  134. this();
  135. addAll(c);
  136. }
  137. /**
  138. * Constructs a new set containing the same elements as the specified
  139. * sorted set, sorted according to the same ordering.
  140. *
  141. * @param s sorted set whose elements will comprise the new set.
  142. * @throws NullPointerException if the specified sorted set is null.
  143. */
  144. public TreeSet(SortedSet<E> s) {
  145. this(s.comparator());
  146. addAll(s);
  147. }
  148. /**
  149. * Returns an iterator over the elements in this set. The elements
  150. * are returned in ascending order.
  151. *
  152. * @return an iterator over the elements in this set.
  153. */
  154. public Iterator<E> iterator() {
  155. return keySet.iterator();
  156. }
  157. /**
  158. * Returns the number of elements in this set (its cardinality).
  159. *
  160. * @return the number of elements in this set (its cardinality).
  161. */
  162. public int size() {
  163. return m.size();
  164. }
  165. /**
  166. * Returns <tt>true</tt> if this set contains no elements.
  167. *
  168. * @return <tt>true</tt> if this set contains no elements.
  169. */
  170. public boolean isEmpty() {
  171. return m.isEmpty();
  172. }
  173. /**
  174. * Returns <tt>true</tt> if this set contains the specified element.
  175. *
  176. * @param o the object to be checked for containment in this set.
  177. * @return <tt>true</tt> if this set contains the specified element.
  178. *
  179. * @throws ClassCastException if the specified object cannot be compared
  180. * with the elements currently in the set.
  181. */
  182. public boolean contains(Object o) {
  183. return m.containsKey(o);
  184. }
  185. /**
  186. * Adds the specified element to this set if it is not already present.
  187. *
  188. * @param o element to be added to this set.
  189. * @return <tt>true</tt> if the set did not already contain the specified
  190. * element.
  191. *
  192. * @throws ClassCastException if the specified object cannot be compared
  193. * with the elements currently in the set.
  194. */
  195. public boolean add(E o) {
  196. return m.put(o, PRESENT)==null;
  197. }
  198. /**
  199. * Removes the specified element from this set if it is present.
  200. *
  201. * @param o object to be removed from this set, if present.
  202. * @return <tt>true</tt> if the set contained the specified element.
  203. *
  204. * @throws ClassCastException if the specified object cannot be compared
  205. * with the elements currently in the set.
  206. */
  207. public boolean remove(Object o) {
  208. return m.remove(o)==PRESENT;
  209. }
  210. /**
  211. * Removes all of the elements from this set.
  212. */
  213. public void clear() {
  214. m.clear();
  215. }
  216. /**
  217. * Adds all of the elements in the specified collection to this set.
  218. *
  219. * @param c elements to be added
  220. * @return <tt>true</tt> if this set changed as a result of the call.
  221. *
  222. * @throws ClassCastException if the elements provided cannot be compared
  223. * with the elements currently in the set.
  224. * @throws NullPointerException of the specified collection is null.
  225. */
  226. public boolean addAll(Collection<? extends E> c) {
  227. // Use linear-time version if applicable
  228. if (m.size()==0 && c.size() > 0 &&
  229. // FIXME(VFORCE) Work-around for bug in compiler
  230. c instanceof SortedSet &&
  231. m instanceof TreeMap) {
  232. SortedSet<Map.Entry<E, Object>> set = (SortedSet<Map.Entry<E, Object>>) (SortedSet) c;
  233. TreeMap<E,Object> map = (TreeMap<E, Object>) m;
  234. Comparator<? super E> cc = (Comparator<E>) set.comparator();
  235. Comparator<? super E> mc = map.comparator();
  236. if (cc==mc || (cc != null && cc.equals(mc))) {
  237. map.addAllForTreeSet(set, PRESENT);
  238. return true;
  239. }
  240. }
  241. return super.addAll(c);
  242. }
  243. /**
  244. * Returns a view of the portion of this set whose elements range from
  245. * <tt>fromElement</tt>, inclusive, to <tt>toElement</tt>, exclusive. (If
  246. * <tt>fromElement</tt> and <tt>toElement</tt> are equal, the returned
  247. * sorted set is empty.) The returned sorted set is backed by this set,
  248. * so changes in the returned sorted set are reflected in this set, and
  249. * vice-versa. The returned sorted set supports all optional Set
  250. * operations.<p>
  251. *
  252. * The sorted set returned by this method will throw an
  253. * <tt>IllegalArgumentException</tt> if the user attempts to insert an
  254. * element outside the specified range.<p>
  255. *
  256. * Note: this method always returns a <i>half-open range</i> (which
  257. * includes its low endpoint but not its high endpoint). If you need a
  258. * <i>closed range</i> (which includes both endpoints), and the element
  259. * type allows for calculation of the successor of a specified value,
  260. * merely request the subrange from <tt>lowEndpoint</tt> to
  261. * <tt>successor(highEndpoint)</tt>. For example, suppose that <tt>s</tt>
  262. * is a sorted set of strings. The following idiom obtains a view
  263. * containing all of the strings in <tt>s</tt> from <tt>low</tt> to
  264. * <tt>high</tt>, inclusive: <pre>
  265. * SortedSet sub = s.subSet(low, high+"\0");
  266. * </pre>
  267. *
  268. * A similar technique can be used to generate an <i>open range</i> (which
  269. * contains neither endpoint). The following idiom obtains a view
  270. * containing all of the strings in <tt>s</tt> from <tt>low</tt> to
  271. * <tt>high</tt>, exclusive: <pre>
  272. * SortedSet sub = s.subSet(low+"\0", high);
  273. * </pre>
  274. *
  275. * @param fromElement low endpoint (inclusive) of the subSet.
  276. * @param toElement high endpoint (exclusive) of the subSet.
  277. * @return a view of the portion of this set whose elements range from
  278. * <tt>fromElement</tt>, inclusive, to <tt>toElement</tt>,
  279. * exclusive.
  280. * @throws ClassCastException if <tt>fromElement</tt> and
  281. * <tt>toElement</tt> cannot be compared to one another using
  282. * this set's comparator (or, if the set has no comparator,
  283. * using natural ordering).
  284. * @throws IllegalArgumentException if <tt>fromElement</tt> is greater than
  285. * <tt>toElement</tt>.
  286. * @throws NullPointerException if <tt>fromElement</tt> or
  287. * <tt>toElement</tt> is <tt>null</tt> and this set uses natural
  288. * order, or its comparator does not tolerate <tt>null</tt>
  289. * elements.
  290. */
  291. public SortedSet<E> subSet(E fromElement, E toElement) {
  292. return new TreeSet<E>(m.subMap(fromElement, toElement));
  293. }
  294. /**
  295. * Returns a view of the portion of this set whose elements are strictly
  296. * less than <tt>toElement</tt>. The returned sorted set is backed by
  297. * this set, so changes in the returned sorted set are reflected in this
  298. * set, and vice-versa. The returned sorted set supports all optional set
  299. * operations.<p>
  300. *
  301. * The sorted set returned by this method will throw an
  302. * <tt>IllegalArgumentException</tt> if the user attempts to insert an
  303. * element greater than or equal to <tt>toElement</tt>.<p>
  304. *
  305. * Note: this method always returns a view that does not contain its
  306. * (high) endpoint. If you need a view that does contain this endpoint,
  307. * and the element type allows for calculation of the successor of a
  308. * specified value, merely request a headSet bounded by
  309. * <tt>successor(highEndpoint)</tt>. For example, suppose that <tt>s</tt>
  310. * is a sorted set of strings. The following idiom obtains a view
  311. * containing all of the strings in <tt>s</tt> that are less than or equal
  312. * to <tt>high</tt>: <pre> SortedSet head = s.headSet(high+"\0");</pre>
  313. *
  314. * @param toElement high endpoint (exclusive) of the headSet.
  315. * @return a view of the portion of this set whose elements are strictly
  316. * less than toElement.
  317. * @throws ClassCastException if <tt>toElement</tt> is not compatible
  318. * with this set's comparator (or, if the set has no comparator,
  319. * if <tt>toElement</tt> does not implement <tt>Comparable</tt>).
  320. * @throws IllegalArgumentException if this set is itself a subSet,
  321. * headSet, or tailSet, and <tt>toElement</tt> is not within the
  322. * specified range of the subSet, headSet, or tailSet.
  323. * @throws NullPointerException if <tt>toElement</tt> is <tt>null</tt> and
  324. * this set uses natural ordering, or its comparator does
  325. * not tolerate <tt>null</tt> elements.
  326. */
  327. public SortedSet<E> headSet(E toElement) {
  328. return new TreeSet<E>(m.headMap(toElement));
  329. }
  330. /**
  331. * Returns a view of the portion of this set whose elements are
  332. * greater than or equal to <tt>fromElement</tt>. The returned sorted set
  333. * is backed by this set, so changes in the returned sorted set are
  334. * reflected in this set, and vice-versa. The returned sorted set
  335. * supports all optional set operations.<p>
  336. *
  337. * The sorted set returned by this method will throw an
  338. * <tt>IllegalArgumentException</tt> if the user attempts to insert an
  339. * element less than <tt>fromElement</tt>.
  340. *
  341. * Note: this method always returns a view that contains its (low)
  342. * endpoint. If you need a view that does not contain this endpoint, and
  343. * the element type allows for calculation of the successor of a specified
  344. * value, merely request a tailSet bounded by
  345. * <tt>successor(lowEndpoint)</tt>. For example, suppose that <tt>s</tt>
  346. * is a sorted set of strings. The following idiom obtains a view
  347. * containing all of the strings in <tt>s</tt> that are strictly greater
  348. * than <tt>low</tt>: <pre>
  349. * SortedSet tail = s.tailSet(low+"\0");
  350. * </pre>
  351. *
  352. * @param fromElement low endpoint (inclusive) of the tailSet.
  353. * @return a view of the portion of this set whose elements are
  354. * greater than or equal to <tt>fromElement</tt>.
  355. * @throws ClassCastException if <tt>fromElement</tt> is not compatible
  356. * with this set's comparator (or, if the set has no comparator,
  357. * if <tt>fromElement</tt> does not implement <tt>Comparable</tt>).
  358. * @throws IllegalArgumentException if this set is itself a subSet,
  359. * headSet, or tailSet, and <tt>fromElement</tt> is not within the
  360. * specified range of the subSet, headSet, or tailSet.
  361. * @throws NullPointerException if <tt>fromElement</tt> is <tt>null</tt>
  362. * and this set uses natural ordering, or its comparator does
  363. * not tolerate <tt>null</tt> elements.
  364. */
  365. public SortedSet<E> tailSet(E fromElement) {
  366. return new TreeSet<E>(m.tailMap(fromElement));
  367. }
  368. /**
  369. * Returns the comparator used to order this sorted set, or <tt>null</tt>
  370. * if this tree set uses its elements natural ordering.
  371. *
  372. * @return the comparator used to order this sorted set, or <tt>null</tt>
  373. * if this tree set uses its elements natural ordering.
  374. */
  375. public Comparator<? super E> comparator() {
  376. return m.comparator();
  377. }
  378. /**
  379. * Returns the first (lowest) element currently in this sorted set.
  380. *
  381. * @return the first (lowest) element currently in this sorted set.
  382. * @throws NoSuchElementException sorted set is empty.
  383. */
  384. public E first() {
  385. return m.firstKey();
  386. }
  387. /**
  388. * Returns the last (highest) element currently in this sorted set.
  389. *
  390. * @return the last (highest) element currently in this sorted set.
  391. * @throws NoSuchElementException sorted set is empty.
  392. */
  393. public E last() {
  394. return m.lastKey();
  395. }
  396. /**
  397. * Returns a shallow copy of this <tt>TreeSet</tt> instance. (The elements
  398. * themselves are not cloned.)
  399. *
  400. * @return a shallow copy of this set.
  401. */
  402. public Object clone() {
  403. TreeSet<E> clone = null;
  404. try {
  405. clone = (TreeSet<E>) super.clone();
  406. } catch (CloneNotSupportedException e) {
  407. throw new InternalError();
  408. }
  409. clone.m = new TreeMap<E,Object>(m);
  410. clone.keySet = clone.m.keySet();
  411. return clone;
  412. }
  413. /**
  414. * Save the state of the <tt>TreeSet</tt> instance to a stream (that is,
  415. * serialize it).
  416. *
  417. * @serialData Emits the comparator used to order this set, or
  418. * <tt>null</tt> if it obeys its elements' natural ordering
  419. * (Object), followed by the size of the set (the number of
  420. * elements it contains) (int), followed by all of its
  421. * elements (each an Object) in order (as determined by the
  422. * set's Comparator, or by the elements' natural ordering if
  423. * the set has no Comparator).
  424. */
  425. private void writeObject(java.io.ObjectOutputStream s)
  426. throws java.io.IOException {
  427. // Write out any hidden stuff
  428. s.defaultWriteObject();
  429. // Write out Comparator
  430. s.writeObject(m.comparator());
  431. // Write out size
  432. s.writeInt(m.size());
  433. // Write out all elements in the proper order.
  434. for (Iterator i=m.keySet().iterator(); i.hasNext(); )
  435. s.writeObject(i.next());
  436. }
  437. /**
  438. * Reconstitute the <tt>TreeSet</tt> instance from a stream (that is,
  439. * deserialize it).
  440. */
  441. private void readObject(java.io.ObjectInputStream s)
  442. throws java.io.IOException, ClassNotFoundException {
  443. // Read in any hidden stuff
  444. s.defaultReadObject();
  445. // Read in Comparator
  446. Comparator<E> c = (Comparator<E>) s.readObject();
  447. // Create backing TreeMap and keySet view
  448. TreeMap<E,Object> tm;
  449. if (c==null)
  450. tm = new TreeMap<E,Object>();
  451. else
  452. tm = new TreeMap<E,Object>(c);
  453. m = tm;
  454. keySet = m.keySet();
  455. // Read in size
  456. int size = s.readInt();
  457. tm.readTreeSet(size, s, PRESENT);
  458. }
  459. private static final long serialVersionUID = -2479143000061671589L;
  460. }