ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/TreeSet.java
Revision: 1.2
Committed: Sun Mar 6 12:06:17 2005 UTC (19 years, 2 months ago) by dl
Branch: MAIN
Changes since 1.1: +7 -7 lines
Log Message:
Copyedit pass

File Contents

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