1. /*
  2. * @(#)TreeSet.java 1.14 01/11/29
  3. *
  4. * Copyright 2002 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. * @author Josh Bloch
  49. * @version 1.14, 11/29/01
  50. * @see Collection
  51. * @see Set
  52. * @see HashSet
  53. * @see Comparable
  54. * @see Comparator
  55. * @see Collections#synchronizedSortedSet(SortedSet)
  56. * @see TreeMap
  57. * @since JDK1.2
  58. */
  59. public class TreeSet extends AbstractSet
  60. implements SortedSet, Cloneable, java.io.Serializable
  61. {
  62. private transient SortedMap m; // The backing Map
  63. private transient Set keySet; // The keySet view of the backing Map
  64. // Dummy value to associate with an Object in the backing Map
  65. private static final Object PRESENT = new Object();
  66. /**
  67. * Constructs a set backed by the given sorted map.
  68. */
  69. private TreeSet(SortedMap m) {
  70. this.m = m;
  71. keySet = m.keySet();
  72. }
  73. /**
  74. * Constructs a new, empty set, sorted according to the elements' natural
  75. * order. All elements inserted into the set must implement the
  76. * <tt>Comparable</tt> interface. Furthermore, all such elements must be
  77. * <i>mutually comparable</i>: <tt>e1.compareTo(e2)</tt> must not throw a
  78. * <tt>ClassCastException</tt> for any elements <tt>e1</tt> and
  79. * <tt>e2</tt> in the set. If the user attempts to add an element to the
  80. * set that violates this constraint (for example, the user attempts to
  81. * add a string element to a set whose elements are integers), the
  82. * <tt>add(Object)</tt> call will throw a <tt>ClassCastException</tt>.
  83. *
  84. * @see Comparable
  85. */
  86. public TreeSet() {
  87. this(new TreeMap());
  88. }
  89. /**
  90. * Constructs a new, empty set, sorted according to the given comparator.
  91. * All elements inserted into the set must be <i>mutually comparable</i>
  92. * by the given comparator: <tt>comparator.compare(e1, e2)</tt> must not
  93. * throw a <tt>ClassCastException</tt> for any elements <tt>e1</tt> and
  94. * <tt>e2</tt> in the set. If the user attempts to add an element to the
  95. * set that violates this constraint, the <tt>add(Object)</tt> call will
  96. * throw a <tt>ClassCastException</tt>.
  97. */
  98. public TreeSet(Comparator c) {
  99. this(new TreeMap(c));
  100. }
  101. /**
  102. * Constructs a new set containing the elements in the specified
  103. * collection, sorted according to the elements' <i>natural order</i>.
  104. * All keys inserted into the set must implement the <tt>Comparable</tt>
  105. * interface. Furthermore, all such keys must be <i>mutually
  106. * comparable</i>: <tt>k1.compareTo(k2)</tt> must not throw a
  107. * <tt>ClassCastException</tt> for any elements <tt>k1</tt> and
  108. * <tt>k2</tt> in the set.
  109. *
  110. * @param c The elements that will comprise the new set.
  111. *
  112. * @throws ClassCastException if the keys in the given collection are not
  113. * comparable, or are not mutually comparable.
  114. */
  115. public TreeSet(Collection c) {
  116. this();
  117. addAll(c);
  118. }
  119. /**
  120. * Constructs a new set containing the same elements as the given sorted
  121. * set, sorted according to the same ordering.
  122. *
  123. * @param s sorted set whose elements will comprise the new set.
  124. */
  125. public TreeSet(SortedSet s) {
  126. this(s.comparator());
  127. addAll(s);
  128. }
  129. /**
  130. * Returns an iterator over the elements in this set. The elements
  131. * are returned in ascending order.
  132. *
  133. * @return an iterator over the elements in this set.
  134. */
  135. public Iterator iterator() {
  136. return keySet.iterator();
  137. }
  138. /**
  139. * Returns the number of elements in this set (its cardinality).
  140. *
  141. * @return the number of elements in this set (its cardinality).
  142. */
  143. public int size() {
  144. return m.size();
  145. }
  146. /**
  147. * Returns <tt>true</tt> if this set contains no elements.
  148. *
  149. * @return <tt>true</tt> if this set contains no elements.
  150. */
  151. public boolean isEmpty() {
  152. return m.isEmpty();
  153. }
  154. /**
  155. * Returns <tt>true</tt> if this set contains the specified element.
  156. *
  157. * @param o the object to be checked for containment in this set.
  158. * @return <tt>true</tt> if this set contains the specified element.
  159. *
  160. * @throws ClassCastException if the specified object cannot be compared
  161. * with the elements currently in the set.
  162. */
  163. public boolean contains(Object o) {
  164. return m.containsKey(o);
  165. }
  166. /**
  167. * Adds the specified element to this set if it is not already present.
  168. *
  169. * @param o element to be added to this set.
  170. * @return <tt>true</tt> if the set did not already contain the specified
  171. * element.
  172. *
  173. * @throws ClassCastException if the specified object cannot be compared
  174. * with the elements currently in the set.
  175. */
  176. public boolean add(Object o) {
  177. return m.put(o, PRESENT)==null;
  178. }
  179. /**
  180. * Removes the given element from this set if it is present.
  181. *
  182. * @param o object to be removed from this set, if present.
  183. * @return <tt>true</tt> if the set contained the specified element.
  184. *
  185. * @throws ClassCastException if the specified object cannot be compared
  186. * with the elements currently in the set.
  187. */
  188. public boolean remove(Object o) {
  189. return m.remove(o)==PRESENT;
  190. }
  191. /**
  192. * Removes all of the elements from this set.
  193. */
  194. public void clear() {
  195. m.clear();
  196. }
  197. /**
  198. * Adds all of the elements in the specified collection to this set.
  199. *
  200. * @param c elements to be added
  201. * @return <tt>true</tt> if this set changed as a result of the call.
  202. *
  203. * @throws ClassCastException if the elements provided cannot be compared
  204. * with the elements currently in the set.
  205. */
  206. public boolean addAll(Collection c) {
  207. // Use linear-time version if applicable
  208. if (m.size()==0 && c.size() > 0 && c instanceof SortedSet &&
  209. m instanceof TreeMap) {
  210. SortedSet set = (SortedSet)c;
  211. TreeMap map = (TreeMap)m;
  212. Comparator cc = set.comparator();
  213. Comparator mc = map.comparator();
  214. if (cc==mc || (cc != null && cc.equals(mc))) {
  215. map.addAllForTreeSet(set, PRESENT);
  216. return true;
  217. }
  218. }
  219. return super.addAll(c);
  220. }
  221. /**
  222. * Returns a view of the portion of this set whose elements range from
  223. * <tt>fromElement</tt>, inclusive, to <tt>toElement</tt>, exclusive. (If
  224. * <tt>fromElement</tt> and <tt>toElement</tt> are equal, the returned
  225. * sorted set is empty.) The returned sorted set is backed by this set,
  226. * so changes in the returned sorted set are reflected in this set, and
  227. * vice-versa. The returned sorted set supports all optional Set
  228. * operations.<p>
  229. *
  230. * The sorted set returned by this method will throw an
  231. * <tt>IllegalArgumentException</tt> if the user attempts to insert an
  232. * element outside the specified range.<p>
  233. *
  234. * Note: this method always returns a <i>half-open range</i> (which
  235. * includes its low endpoint but not its high endpoint). If you need a
  236. * <i>closed range</i> (which includes both endpoints), and the element
  237. * type allows for calculation of the successor a given value, merely
  238. * request the subrange from <tt>lowEndpoint</tt> to
  239. * <tt>successor(highEndpoint)</tt>. For example, suppose that <tt>s</tt>
  240. * is a sorted set of strings. The following idiom obtains a view
  241. * containing all of the strings in <tt>s</tt> from <tt>low</tt> to
  242. * <tt>high</tt>, inclusive: <pre>
  243. * SortedSet sub = s.subSet(low, high+"\0");
  244. * </pre>
  245. *
  246. * A similar technique can be used to generate an <i>open range</i> (which
  247. * contains neither endpoint). 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>, exclusive: <pre>
  250. * SortedSet sub = s.subSet(low+"\0", high);
  251. * </pre>
  252. *
  253. * @param fromElement low endpoint (inclusive) of the subSet.
  254. * @param toElement high endpoint (exclusive) of the subSet.
  255. * @return a view of the portion of this set whose elements range from
  256. * <tt>fromElement</tt>, inclusive, to <tt>toElement</tt>,
  257. * exclusive.
  258. * @throws NullPointerException if <tt>fromElement</tt> or
  259. * <tt>toElement</tt> is <tt>null</tt> and this set uses
  260. * natural ordering, or its comparator does not tolerate
  261. * <tt>null</tt> elements.
  262. * @throws IllegalArgumentException if <tt>fromElement</tt> is greater
  263. * than <tt>toElement</tt>.
  264. */
  265. public SortedSet subSet(Object fromElement, Object toElement) {
  266. return new TreeSet(m.subMap(fromElement, toElement));
  267. }
  268. /**
  269. * Returns a view of the portion of this set whose elements are strictly
  270. * less than <tt>toElement</tt>. The returned sorted set is backed by
  271. * this set, so changes in the returned sorted set are reflected in this
  272. * set, and vice-versa. The returned sorted set supports all optional set
  273. * operations.<p>
  274. *
  275. * The sorted set returned by this method will throw an
  276. * <tt>IllegalArgumentException</tt> if the user attempts to insert an
  277. * element greater than or equal to <tt>toElement</tt>.<p>
  278. *
  279. * Note: this method always returns a view that does not contain its
  280. * (high) endpoint. If you need a view that does contain this endpoint,
  281. * and the element type allows for calculation of the successor a given
  282. * value, merely request a headSet bounded by
  283. * <tt>successor(highEndpoint)</tt>. For example, suppose that <tt>s</tt>
  284. * is a sorted set of strings. The following idiom obtains a view
  285. * containing all of the strings in <tt>s</tt> that are less than or equal
  286. * to <tt>high</tt>: <pre> SortedSet head = s.headSet(high+"\0");</pre>
  287. *
  288. * @param toElement high endpoint (exclusive) of the headSet.
  289. * @return a view of the portion of this set whose elements are strictly
  290. * less than toElement.
  291. * @throws NullPointerException if toElement is <tt>null</tt> and this
  292. * set uses natural ordering, or its comparator does
  293. * not tolerate <tt>null</tt> elements.
  294. */
  295. public SortedSet headSet(Object toElement) {
  296. return new TreeSet(m.headMap(toElement));
  297. }
  298. /**
  299. * Returns a view of the portion of this set whose elements are
  300. * greater than or equal to <tt>fromElement</tt>. The returned sorted set
  301. * is backed by this set, so changes in the returned sorted set are
  302. * reflected in this set, and vice-versa. The returned sorted set
  303. * supports all optional set operations.<p>
  304. *
  305. * The sorted set returned by this method will throw an
  306. * <tt>IllegalArgumentException</tt> if the user attempts to insert an
  307. * element less than <tt>fromElement</tt>.
  308. *
  309. * Note: this method always returns a view that contains its (low)
  310. * endpoint. If you need a view that does not contain this endpoint, and
  311. * the element type allows for calculation of the successor a given value,
  312. * merely request a tailSet bounded by <tt>successor(lowEndpoint)</tt>.
  313. * For example, suppose that <tt>s</tt> is a sorted set of strings. The
  314. * following idiom obtains a view containing all of the strings in
  315. * <tt>s</tt> that are strictly greater than <tt>low</tt>: <pre>
  316. * SortedSet tail = s.tailSet(low+"\0");
  317. * </pre>
  318. *
  319. * @param fromElement low endpoint (inclusive) of the tailSet.
  320. * @return a view of the portion of this set whose elements are
  321. * greater than or equal to <tt>fromElement</tt>.
  322. *
  323. * @throws NullPointerException if <tt>fromElement</tt> is <tt>null</tt>
  324. * and this set uses natural ordering, or its comparator
  325. * does not tolerate <tt>null</tt> elements.
  326. */
  327. public SortedSet tailSet(Object fromElement) {
  328. return new TreeSet(m.tailMap(fromElement));
  329. }
  330. /**
  331. * Returns the comparator used to order this sorted set, or <tt>null</tt>
  332. * if this tree map uses its keys natural ordering.
  333. *
  334. * @return the comparator used to order this sorted set, or <tt>null</tt>
  335. * if this tree map uses its keys natural ordering.
  336. */
  337. public Comparator comparator() {
  338. return m.comparator();
  339. }
  340. /**
  341. * Returns the first (lowest) element currently in this sorted set.
  342. *
  343. * @return the first (lowest) element currently in this sorted set.
  344. * @throws NoSuchElementException sorted set is empty.
  345. */
  346. public Object first() {
  347. return m.firstKey();
  348. }
  349. /**
  350. * Returns the last (highest) element currently in this sorted set.
  351. *
  352. * @return the last (highest) element currently in this sorted set.
  353. * @throws NoSuchElementException sorted set is empty.
  354. */
  355. public Object last() {
  356. return m.lastKey();
  357. }
  358. /**
  359. * Returns a shallow copy of this <tt>TreeSet</tt> instance. (The elements
  360. * themselves are not cloned.)
  361. *
  362. * @return a shallow copy of this set.
  363. */
  364. public Object clone() {
  365. return new TreeSet(this);
  366. }
  367. /**
  368. * Save the state of the <tt>TreeSet</tt> instance to a stream (that is,
  369. * serialize it).
  370. *
  371. * @serialData Emits the comparator used to order this set, or
  372. * <tt>null</tt> if it obeys its elements' natural ordering
  373. * (Object), followed by the size of the set (the number of
  374. * elements it contains) (int), followed by all of its
  375. * elements (each an Object) in order (as determined by the
  376. * set's Comparator, or by the elements' natural ordering if
  377. * the set has no Comparator).
  378. */
  379. private synchronized void writeObject(java.io.ObjectOutputStream s)
  380. throws java.io.IOException {
  381. // Write out any hidden stuff
  382. s.defaultWriteObject();
  383. // Write out Comparator
  384. s.writeObject(m.comparator());
  385. // Write out size
  386. s.writeInt(m.size());
  387. // Write out all elements in the proper order.
  388. for (Iterator i=m.keySet().iterator(); i.hasNext(); )
  389. s.writeObject(i.next());
  390. }
  391. /**
  392. * Reconstitute the <tt>TreeSet</tt> instance from a stream (that is,
  393. * deserialize it).
  394. */
  395. private synchronized void readObject(java.io.ObjectInputStream s)
  396. throws java.io.IOException, ClassNotFoundException {
  397. // Read in any hidden stuff
  398. s.defaultReadObject();
  399. // Read in Comparator
  400. Comparator c = (Comparator)s.readObject();
  401. // Create backing TreeMap and keySet view
  402. m = (c==null ? new TreeMap() : new TreeMap(c));
  403. keySet = m.keySet();
  404. // Read in size
  405. int size = s.readInt();
  406. ((TreeMap)m).readTreeSet(size, s, PRESENT);
  407. }
  408. }