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