TreeSet.java 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642
  1. /* TreeSet.java -- a class providing a TreeMap-backed SortedSet
  2. Copyright (C) 1999, 2000, 2001, 2004, 2005 Free Software Foundation, Inc.
  3. This file is part of GNU Classpath.
  4. GNU Classpath is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2, or (at your option)
  7. any later version.
  8. GNU Classpath is distributed in the hope that it will be useful, but
  9. WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with GNU Classpath; see the file COPYING. If not, write to the
  14. Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  15. 02110-1301 USA.
  16. Linking this library statically or dynamically with other modules is
  17. making a combined work based on this library. Thus, the terms and
  18. conditions of the GNU General Public License cover the whole
  19. combination.
  20. As a special exception, the copyright holders of this library give you
  21. permission to link this library with independent modules to produce an
  22. executable, regardless of the license terms of these independent
  23. modules, and to copy and distribute the resulting executable under
  24. terms of your choice, provided that you also meet, for each linked
  25. independent module, the terms and conditions of the license of that
  26. module. An independent module is a module which is not derived from
  27. or based on this library. If you modify this library, you may extend
  28. this exception to your version of the library, but you are not
  29. obligated to do so. If you do not wish to do so, delete this
  30. exception statement from your version. */
  31. package java.util;
  32. import java.io.IOException;
  33. import java.io.ObjectInputStream;
  34. import java.io.ObjectOutputStream;
  35. import java.io.Serializable;
  36. /**
  37. * This class provides a TreeMap-backed implementation of the SortedSet
  38. * interface. The elements will be sorted according to their <i>natural
  39. * order</i>, or according to the provided <code>Comparator</code>.<p>
  40. *
  41. * Most operations are O(log n), but there is so much overhead that this
  42. * makes small sets expensive. Note that the ordering must be <i>consistent
  43. * with equals</i> to correctly implement the Set interface. If this
  44. * condition is violated, the set is still well-behaved, but you may have
  45. * suprising results when comparing it to other sets.<p>
  46. *
  47. * This implementation is not synchronized. If you need to share this between
  48. * multiple threads, do something like:<br>
  49. * <code>SortedSet s
  50. * = Collections.synchronizedSortedSet(new TreeSet(...));</code><p>
  51. *
  52. * The iterators are <i>fail-fast</i>, meaning that any structural
  53. * modification, except for <code>remove()</code> called on the iterator
  54. * itself, cause the iterator to throw a
  55. * <code>ConcurrentModificationException</code> rather than exhibit
  56. * non-deterministic behavior.
  57. *
  58. * @author Jon Zeppieri
  59. * @author Bryce McKinlay
  60. * @author Eric Blake (ebb9@email.byu.edu)
  61. * @author Tom Tromey (tromey@redhat.com)
  62. * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
  63. * @see Collection
  64. * @see Set
  65. * @see HashSet
  66. * @see LinkedHashSet
  67. * @see Comparable
  68. * @see Comparator
  69. * @see Collections#synchronizedSortedSet(SortedSet)
  70. * @see TreeMap
  71. * @since 1.2
  72. * @status updated to 1.6
  73. */
  74. public class TreeSet<T> extends AbstractSet<T>
  75. implements NavigableSet<T>, Cloneable, Serializable
  76. {
  77. /**
  78. * Compatible with JDK 1.2.
  79. */
  80. private static final long serialVersionUID = -2479143000061671589L;
  81. /**
  82. * The NavigableMap which backs this Set.
  83. */
  84. // Not final because of readObject. This will always be one of TreeMap or
  85. // TreeMap.SubMap, which both extend AbstractMap.
  86. private transient NavigableMap<T, String> map;
  87. /**
  88. * Construct a new TreeSet whose backing TreeMap using the "natural"
  89. * ordering of keys. Elements that are not mutually comparable will cause
  90. * ClassCastExceptions down the road.
  91. *
  92. * @see Comparable
  93. */
  94. public TreeSet()
  95. {
  96. map = new TreeMap<T, String>();
  97. }
  98. /**
  99. * Construct a new TreeSet whose backing TreeMap uses the supplied
  100. * Comparator. Elements that are not mutually comparable will cause
  101. * ClassCastExceptions down the road.
  102. *
  103. * @param comparator the Comparator this Set will use
  104. */
  105. public TreeSet(Comparator<? super T> comparator)
  106. {
  107. map = new TreeMap<T, String>(comparator);
  108. }
  109. /**
  110. * Construct a new TreeSet whose backing TreeMap uses the "natural"
  111. * orering of the keys and which contains all of the elements in the
  112. * supplied Collection. This runs in n*log(n) time.
  113. *
  114. * @param collection the new Set will be initialized with all
  115. * of the elements in this Collection
  116. * @throws ClassCastException if the elements of the collection are not
  117. * comparable
  118. * @throws NullPointerException if the collection is null
  119. * @see Comparable
  120. */
  121. public TreeSet(Collection<? extends T> collection)
  122. {
  123. map = new TreeMap<T, String>();
  124. addAll(collection);
  125. }
  126. /**
  127. * Construct a new TreeSet, using the same key ordering as the supplied
  128. * SortedSet and containing all of the elements in the supplied SortedSet.
  129. * This constructor runs in linear time.
  130. *
  131. * @param sortedSet the new TreeSet will use this SortedSet's comparator
  132. * and will initialize itself with all its elements
  133. * @throws NullPointerException if sortedSet is null
  134. */
  135. public TreeSet(SortedSet<T> sortedSet)
  136. {
  137. Iterator<T> itr;
  138. map = new TreeMap<T, String>
  139. ((Comparator<? super T>)sortedSet.comparator());
  140. itr = ((SortedSet<T>) sortedSet).iterator();
  141. ((TreeMap<T, String>) map).putKeysLinear(itr, sortedSet.size());
  142. }
  143. /**
  144. * This private constructor is used to implement the subSet() calls around
  145. * a backing TreeMap.SubMap.
  146. *
  147. * @param backingMap the submap
  148. */
  149. private TreeSet(NavigableMap<T,String> backingMap)
  150. {
  151. map = backingMap;
  152. }
  153. /**
  154. * Adds the spplied Object to the Set if it is not already in the Set;
  155. * returns true if the element is added, false otherwise.
  156. *
  157. * @param obj the Object to be added to this Set
  158. * @throws ClassCastException if the element cannot be compared with objects
  159. * already in the set
  160. */
  161. public boolean add(T obj)
  162. {
  163. return map.put(obj, "") == null;
  164. }
  165. /**
  166. * Adds all of the elements in the supplied Collection to this TreeSet.
  167. *
  168. * @param c The collection to add
  169. * @return true if the Set is altered, false otherwise
  170. * @throws NullPointerException if c is null
  171. * @throws ClassCastException if an element in c cannot be compared with
  172. * objects already in the set
  173. */
  174. public boolean addAll(Collection<? extends T> c)
  175. {
  176. boolean result = false;
  177. int pos = c.size();
  178. Iterator<? extends T> itr = c.iterator();
  179. while (--pos >= 0)
  180. result |= (map.put(itr.next(), "") == null);
  181. return result;
  182. }
  183. /**
  184. * Removes all elements in this Set.
  185. */
  186. public void clear()
  187. {
  188. map.clear();
  189. }
  190. /**
  191. * Returns a shallow copy of this Set. The elements are not cloned.
  192. *
  193. * @return the cloned set
  194. */
  195. public Object clone()
  196. {
  197. TreeSet<T> copy = null;
  198. try
  199. {
  200. copy = (TreeSet<T>) super.clone();
  201. // Map may be either TreeMap or TreeMap.SubMap, hence the ugly casts.
  202. copy.map = (NavigableMap<T, String>) ((AbstractMap<T, String>) map).clone();
  203. }
  204. catch (CloneNotSupportedException x)
  205. {
  206. // Impossible result.
  207. }
  208. return copy;
  209. }
  210. /**
  211. * Returns this Set's comparator.
  212. *
  213. * @return the comparator, or null if the set uses natural ordering
  214. */
  215. public Comparator<? super T> comparator()
  216. {
  217. return map.comparator();
  218. }
  219. /**
  220. * Returns true if this Set contains the supplied Object, false otherwise.
  221. *
  222. * @param obj the Object to check for
  223. * @return true if it is in the set
  224. * @throws ClassCastException if obj cannot be compared with objects
  225. * already in the set
  226. */
  227. public boolean contains(Object obj)
  228. {
  229. return map.containsKey(obj);
  230. }
  231. /**
  232. * Returns the first (by order) element in this Set.
  233. *
  234. * @return the first element
  235. * @throws NoSuchElementException if the set is empty
  236. */
  237. public T first()
  238. {
  239. return map.firstKey();
  240. }
  241. /**
  242. * Returns a view of this Set including all elements less than
  243. * <code>to</code>. The returned set is backed by the original, so changes
  244. * in one appear in the other. The subset will throw an
  245. * {@link IllegalArgumentException} for any attempt to access or add an
  246. * element beyond the specified cutoff. The returned set does not include
  247. * the endpoint; if you want inclusion, pass the successor element or
  248. * call {@link #headSet(T,boolean)}. This call is equivalent to
  249. * <code>headSet(to, false)</code>.
  250. *
  251. * @param to the (exclusive) cutoff point
  252. * @return a view of the set less than the cutoff
  253. * @throws ClassCastException if <code>to</code> is not compatible with
  254. * the comparator (or is not Comparable, for natural ordering)
  255. * @throws NullPointerException if to is null, but the comparator does not
  256. * tolerate null elements
  257. */
  258. public SortedSet<T> headSet(T to)
  259. {
  260. return headSet(to, false);
  261. }
  262. /**
  263. * Returns a view of this Set including all elements less than
  264. * (or equal to, if <code>inclusive</code> is true) <code>to</code>.
  265. * The returned set is backed by the original, so changes
  266. * in one appear in the other. The subset will throw an
  267. * {@link IllegalArgumentException} for any attempt to access or add an
  268. * element beyond the specified cutoff.
  269. *
  270. * @param to the cutoff point
  271. * @param inclusive true if <code>to</code> should be included.
  272. * @return a view of the set for the specified range.
  273. * @throws ClassCastException if <code>to</code> is not compatible with
  274. * the comparator (or is not Comparable, for natural ordering)
  275. * @throws NullPointerException if to is null, but the comparator does not
  276. * tolerate null elements
  277. */
  278. public NavigableSet<T> headSet(T to, boolean inclusive)
  279. {
  280. return new TreeSet<T>(map.headMap(to, inclusive));
  281. }
  282. /**
  283. * Returns true if this Set has size 0, false otherwise.
  284. *
  285. * @return true if the set is empty
  286. */
  287. public boolean isEmpty()
  288. {
  289. return map.isEmpty();
  290. }
  291. /**
  292. * Returns in Iterator over the elements in this TreeSet, which traverses
  293. * in ascending order.
  294. *
  295. * @return an iterator
  296. */
  297. public Iterator<T> iterator()
  298. {
  299. return map.keySet().iterator();
  300. }
  301. /**
  302. * Returns the last (by order) element in this Set.
  303. *
  304. * @return the last element
  305. * @throws NoSuchElementException if the set is empty
  306. */
  307. public T last()
  308. {
  309. return map.lastKey();
  310. }
  311. /**
  312. * If the supplied Object is in this Set, it is removed, and true is
  313. * returned; otherwise, false is returned.
  314. *
  315. * @param obj the Object to remove from this Set
  316. * @return true if the set was modified
  317. * @throws ClassCastException if obj cannot be compared to set elements
  318. */
  319. public boolean remove(Object obj)
  320. {
  321. return map.remove(obj) != null;
  322. }
  323. /**
  324. * Returns the number of elements in this Set
  325. *
  326. * @return the set size
  327. */
  328. public int size()
  329. {
  330. return map.size();
  331. }
  332. /**
  333. * Returns a view of this Set including all elements greater or equal to
  334. * <code>from</code> and less than <code>to</code> (a half-open interval).
  335. * The returned set is backed by the original, so changes in one appear in
  336. * the other. The subset will throw an {@link IllegalArgumentException}
  337. * for any attempt to access or add an element beyond the specified cutoffs.
  338. * The returned set includes the low endpoint but not the high; if you want
  339. * to reverse this behavior on either end, pass in the successor element
  340. * or call {@link #subSet(T,boolean,T,boolean)}. This is equivalent to
  341. * calling <code>subSet(from,true,to,false)</code>.
  342. *
  343. * @param from the (inclusive) low cutoff point
  344. * @param to the (exclusive) high cutoff point
  345. * @return a view of the set between the cutoffs
  346. * @throws ClassCastException if either cutoff is not compatible with
  347. * the comparator (or is not Comparable, for natural ordering)
  348. * @throws NullPointerException if from or to is null, but the comparator
  349. * does not tolerate null elements
  350. * @throws IllegalArgumentException if from is greater than to
  351. */
  352. public SortedSet<T> subSet(T from, T to)
  353. {
  354. return subSet(from, true, to, false);
  355. }
  356. /**
  357. * Returns a view of this Set including all elements greater than (or equal to,
  358. * if <code>fromInclusive</code> is true</code> <code>from</code> and less than
  359. * (or equal to, if <code>toInclusive</code> is true) <code>to</code>.
  360. * The returned set is backed by the original, so changes in one appear in
  361. * the other. The subset will throw an {@link IllegalArgumentException}
  362. * for any attempt to access or add an element beyond the specified cutoffs.
  363. *
  364. * @param from the low cutoff point
  365. * @param fromInclusive true if <code>from</code> should be included.
  366. * @param to the high cutoff point
  367. * @param toInclusive true if <code>to</code> should be included.
  368. * @return a view of the set for the specified range.
  369. * @throws ClassCastException if either cutoff is not compatible with
  370. * the comparator (or is not Comparable, for natural ordering)
  371. * @throws NullPointerException if from or to is null, but the comparator
  372. * does not tolerate null elements
  373. * @throws IllegalArgumentException if from is greater than to
  374. */
  375. public NavigableSet<T> subSet(T from, boolean fromInclusive,
  376. T to, boolean toInclusive)
  377. {
  378. return new TreeSet<T>(map.subMap(from, fromInclusive,
  379. to, toInclusive));
  380. }
  381. /**
  382. * Returns a view of this Set including all elements greater or equal to
  383. * <code>from</code>. The returned set is backed by the original, so
  384. * changes in one appear in the other. The subset will throw an
  385. * {@link IllegalArgumentException} for any attempt to access or add an
  386. * element beyond the specified cutoff. The returned set includes the
  387. * endpoint; if you want to exclude it, pass in the successor element
  388. * or call {@link #tailSet(T,boolean)}. This is equivalent to calling
  389. * <code>tailSet(from, true)</code>.
  390. *
  391. * @param from the (inclusive) low cutoff point
  392. * @return a view of the set above the cutoff
  393. * @throws ClassCastException if <code>from</code> is not compatible with
  394. * the comparator (or is not Comparable, for natural ordering)
  395. * @throws NullPointerException if from is null, but the comparator
  396. * does not tolerate null elements
  397. */
  398. public SortedSet<T> tailSet(T from)
  399. {
  400. return tailSet(from, true);
  401. }
  402. /**
  403. * Returns a view of this Set including all elements greater (or equal to,
  404. * if <code>inclusive</code> is true) <code>from</code>. The returned set
  405. * is backed by the original, so changes in one appear in the other. The
  406. * subset will throw an {@link IllegalArgumentException} for any attempt
  407. * to access or add an element beyond the specified cutoff.
  408. *
  409. * @param from the low cutoff point.
  410. * @param inclusive true if <code>from</code> should be included.
  411. * @return a view of the set for the specified range.
  412. * @throws ClassCastException if <code>from</code> is not compatible with
  413. * the comparator (or is not Comparable, for natural ordering)
  414. * @throws NullPointerException if from is null, but the comparator
  415. * does not tolerate null elements
  416. */
  417. public NavigableSet<T> tailSet(T from, boolean inclusive)
  418. {
  419. return new TreeSet<T>(map.tailMap(from, inclusive));
  420. }
  421. /**
  422. * Serializes this object to the given stream.
  423. *
  424. * @param s the stream to write to
  425. * @throws IOException if the underlying stream fails
  426. * @serialData the <i>comparator</i> (Object), followed by the set size
  427. * (int), the the elements in sorted order (Object)
  428. */
  429. private void writeObject(ObjectOutputStream s) throws IOException
  430. {
  431. s.defaultWriteObject();
  432. Iterator<T> itr = map.keySet().iterator();
  433. int pos = map.size();
  434. s.writeObject(map.comparator());
  435. s.writeInt(pos);
  436. while (--pos >= 0)
  437. s.writeObject(itr.next());
  438. }
  439. /**
  440. * Deserializes this object from the given stream.
  441. *
  442. * @param s the stream to read from
  443. * @throws ClassNotFoundException if the underlying stream fails
  444. * @throws IOException if the underlying stream fails
  445. * @serialData the <i>comparator</i> (Object), followed by the set size
  446. * (int), the the elements in sorted order (Object)
  447. */
  448. private void readObject(ObjectInputStream s)
  449. throws IOException, ClassNotFoundException
  450. {
  451. s.defaultReadObject();
  452. Comparator<? super T> comparator = (Comparator<? super T>) s.readObject();
  453. int size = s.readInt();
  454. map = new TreeMap<T, String>(comparator);
  455. ((TreeMap<T, String>) map).putFromObjStream(s, size, false);
  456. }
  457. /**
  458. * Returns the least or lowest element in the set greater than or
  459. * equal to the given element, or <code>null</code> if there is
  460. * no such element.
  461. *
  462. * @param e the element relative to the returned element.
  463. * @return the least element greater than or equal
  464. * to the given element, or <code>null</code> if there is
  465. * no such element.
  466. * @throws ClassCastException if the specified element can not
  467. * be compared with those in the map.
  468. * @throws NullPointerException if the element is <code>null</code>
  469. * and this set either uses natural
  470. * ordering or a comparator that does
  471. * not permit null elements.
  472. * @since 1.6
  473. */
  474. public T ceiling(T e)
  475. {
  476. return map.ceilingKey(e);
  477. }
  478. /**
  479. * Returns an iterator over the elements of this set in descending
  480. * order. This is equivalent to calling
  481. * <code>descendingSet().iterator()</code>.
  482. *
  483. * @return an iterator over the elements in descending order.
  484. * @since 1.6
  485. */
  486. public Iterator<T> descendingIterator()
  487. {
  488. return descendingSet().iterator();
  489. }
  490. /**
  491. * Returns a view of the set in reverse order. The descending set
  492. * is backed by the original set, so that changes affect both sets.
  493. * Any changes occurring to either set while an iteration is taking
  494. * place (with the exception of a {@link Iterator#remove()} operation)
  495. * result in undefined behaviour from the iteration. The ordering
  496. * of the descending set is the same as for a set with a
  497. * {@link Comparator} given by {@link Collections#reverseOrder()},
  498. * and calling {@link #descendingSet()} on the descending set itself
  499. * results in a view equivalent to the original set.
  500. *
  501. * @return a reverse order view of the set.
  502. * @since 1.6
  503. */
  504. public NavigableSet<T> descendingSet()
  505. {
  506. return map.descendingKeySet();
  507. }
  508. /**
  509. * Returns the greatest or highest element in the set less than or
  510. * equal to the given element, or <code>null</code> if there is
  511. * no such element.
  512. *
  513. * @param e the element relative to the returned element.
  514. * @return the greatest element less than or equal
  515. * to the given element, or <code>null</code> if there is
  516. * no such element.
  517. * @throws ClassCastException if the specified element can not
  518. * be compared with those in the map.
  519. * @throws NullPointerException if the element is <code>null</code>
  520. * and this set either uses natural
  521. * ordering or a comparator that does
  522. * not permit null elements.
  523. * @since 1.6
  524. */
  525. public T floor(T e)
  526. {
  527. return map.floorKey(e);
  528. }
  529. /**
  530. * Returns the least or lowest element in the set strictly greater
  531. * than the given element, or <code>null</code> if there is
  532. * no such element.
  533. *
  534. * @param e the element relative to the returned element.
  535. * @return the least element greater than
  536. * the given element, or <code>null</code> if there is
  537. * no such element.
  538. * @throws ClassCastException if the specified element can not
  539. * be compared with those in the map.
  540. * @throws NullPointerException if the element is <code>null</code>
  541. * and this set either uses natural
  542. * ordering or a comparator that does
  543. * not permit null elements.
  544. * @since 1.6
  545. */
  546. public T higher(T e)
  547. {
  548. return map.higherKey(e);
  549. }
  550. /**
  551. * Returns the greatest or highest element in the set strictly less
  552. * than the given element, or <code>null</code> if there is
  553. * no such element.
  554. *
  555. * @param e the element relative to the returned element.
  556. * @return the greatest element less than
  557. * the given element, or <code>null</code> if there is
  558. * no such element.
  559. * @throws ClassCastException if the specified element can not
  560. * be compared with those in the map.
  561. * @throws NullPointerException if the element is <code>null</code>
  562. * and this set either uses natural
  563. * ordering or a comparator that does
  564. * not permit null elements.
  565. * @since 1.6
  566. */
  567. public T lower(T e)
  568. {
  569. return map.lowerKey(e);
  570. }
  571. /**
  572. * Removes and returns the least or lowest element in the set,
  573. * or <code>null</code> if the map is empty.
  574. *
  575. * @return the removed first element, or <code>null</code> if the
  576. * map is empty.
  577. * @since 1.6
  578. */
  579. public T pollFirst()
  580. {
  581. return map.pollFirstEntry().getKey();
  582. }
  583. /**
  584. * Removes and returns the greatest or highest element in the set,
  585. * or <code>null</code> if the map is empty.
  586. *
  587. * @return the removed last element, or <code>null</code> if the
  588. * map is empty.
  589. * @since 1.6
  590. */
  591. public T pollLast()
  592. {
  593. return map.pollLastEntry().getKey();
  594. }
  595. }