ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/TreeSet.java
Revision: 1.27
Committed: Sun May 18 23:47:56 2008 UTC (16 years ago) by jsr166
Branch: MAIN
Changes since 1.26: +39 -39 lines
Log Message:
Sync with OpenJDK; untabify

File Contents

# User Rev Content
1 dl 1.1 /*
2 jsr166 1.26 * Copyright 1998-2006 Sun Microsystems, Inc. All Rights Reserved.
3     * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 dl 1.1 *
5 jsr166 1.26 * This code is free software; you can redistribute it and/or modify it
6     * under the terms of the GNU General Public License version 2 only, as
7     * published by the Free Software Foundation. Sun designates this
8     * particular file as subject to the "Classpath" exception as provided
9     * by Sun in the LICENSE file that accompanied this code.
10     *
11     * This code is distributed in the hope that it will be useful, but WITHOUT
12     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13     * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14     * version 2 for more details (a copy is included in the LICENSE file that
15     * accompanied this code).
16     *
17     * You should have received a copy of the GNU General Public License version
18     * 2 along with this work; if not, write to the Free Software Foundation,
19     * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20     *
21     * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
22     * CA 95054 USA or visit www.sun.com if you need additional information or
23     * have any questions.
24 dl 1.1 */
25    
26 jsr166 1.8 package java.util;
27 dl 1.1
28     /**
29 jsr166 1.11 * A {@link NavigableSet} implementation based on a {@link TreeMap}.
30     * The elements are ordered using their {@linkplain Comparable natural
31     * ordering}, or by a {@link Comparator} provided at set creation
32     * time, depending on which constructor is used.
33 dl 1.1 *
34 jsr166 1.11 * <p>This implementation provides guaranteed log(n) time cost for the basic
35 dl 1.21 * operations ({@code add}, {@code remove} and {@code contains}).
36 dl 1.1 *
37 jsr166 1.11 * <p>Note that the ordering maintained by a set (whether or not an explicit
38 dl 1.1 * comparator is provided) must be <i>consistent with equals</i> if it is to
39 dl 1.21 * correctly implement the {@code Set} interface. (See {@code Comparable}
40     * or {@code Comparator} for a precise definition of <i>consistent with
41     * equals</i>.) This is so because the {@code Set} interface is defined in
42     * terms of the {@code equals} operation, but a {@code TreeSet} instance
43     * performs all element comparisons using its {@code compareTo} (or
44     * {@code compare}) method, so two elements that are deemed equal by this method
45 dl 1.1 * are, from the standpoint of the set, equal. The behavior of a set
46     * <i>is</i> well-defined even if its ordering is inconsistent with equals; it
47 dl 1.21 * just fails to obey the general contract of the {@code Set} interface.
48 dl 1.1 *
49 jsr166 1.18 * <p><strong>Note that this implementation is not synchronized.</strong>
50     * If multiple threads access a tree set concurrently, and at least one
51     * of the threads modifies the set, it <i>must</i> be synchronized
52     * externally. This is typically accomplished by synchronizing on some
53     * object that naturally encapsulates the set.
54     * If no such object exists, the set should be "wrapped" using the
55     * {@link Collections#synchronizedSortedSet Collections.synchronizedSortedSet}
56     * method. This is best done at creation time, to prevent accidental
57     * unsynchronized access to the set: <pre>
58     * SortedSet s = Collections.synchronizedSortedSet(new TreeSet(...));</pre>
59 dl 1.1 *
60 dl 1.21 * <p>The iterators returned by this class's {@code iterator} method are
61 dl 1.1 * <i>fail-fast</i>: if the set is modified at any time after the iterator is
62 dl 1.21 * created, in any way except through the iterator's own {@code remove}
63 jsr166 1.11 * method, the iterator will throw a {@link ConcurrentModificationException}.
64 dl 1.1 * Thus, in the face of concurrent modification, the iterator fails quickly
65     * and cleanly, rather than risking arbitrary, non-deterministic behavior at
66     * an undetermined time in the future.
67     *
68     * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
69     * as it is, generally speaking, impossible to make any hard guarantees in the
70     * presence of unsynchronized concurrent modification. Fail-fast iterators
71 dl 1.21 * throw {@code ConcurrentModificationException} on a best-effort basis.
72 dl 1.1 * Therefore, it would be wrong to write a program that depended on this
73     * exception for its correctness: <i>the fail-fast behavior of iterators
74 jsr166 1.10 * should be used only to detect bugs.</i>
75 dl 1.1 *
76 jsr166 1.10 * <p>This class is a member of the
77 jsr166 1.24 * <a href="{@docRoot}/../technotes/guides/collections/index.html">
78 dl 1.1 * Java Collections Framework</a>.
79     *
80 jsr166 1.11 * @param <E> the type of elements maintained by this set
81     *
82 dl 1.1 * @author Josh Bloch
83     * @version %I%, %G%
84 jsr166 1.27 * @see Collection
85     * @see Set
86     * @see HashSet
87 dl 1.1 * @see Comparable
88     * @see Comparator
89 jsr166 1.27 * @see TreeMap
90 dl 1.1 * @since 1.2
91     */
92    
93 dl 1.21 public class TreeSet<E> extends AbstractSet<E>
94 dl 1.1 implements NavigableSet<E>, Cloneable, java.io.Serializable
95     {
96 dl 1.22 /**
97 dl 1.21 * The backing map.
98     */
99 dl 1.22 private transient NavigableMap<E,Object> m;
100 dl 1.1
101     // Dummy value to associate with an Object in the backing Map
102     private static final Object PRESENT = new Object();
103    
104     /**
105 jsr166 1.11 * Constructs a set backed by the specified navigable map.
106 dl 1.1 */
107 dl 1.21 TreeSet(NavigableMap<E,Object> m) {
108 dl 1.1 this.m = m;
109     }
110    
111     /**
112 jsr166 1.11 * Constructs a new, empty tree set, sorted according to the
113     * natural ordering of its elements. All elements inserted into
114     * the set must implement the {@link Comparable} interface.
115     * Furthermore, all such elements must be <i>mutually
116 dl 1.21 * comparable</i>: {@code e1.compareTo(e2)} must not throw a
117     * {@code ClassCastException} for any elements {@code e1} and
118     * {@code e2} in the set. If the user attempts to add an element
119 jsr166 1.11 * to the set that violates this constraint (for example, the user
120     * attempts to add a string element to a set whose elements are
121 jsr166 1.24 * integers), the {@code add} call will throw a
122 dl 1.21 * {@code ClassCastException}.
123 dl 1.1 */
124     public TreeSet() {
125 jsr166 1.27 this(new TreeMap<E,Object>());
126 dl 1.1 }
127    
128     /**
129 jsr166 1.12 * Constructs a new, empty tree set, sorted according to the specified
130     * comparator. All elements inserted into the set must be <i>mutually
131 dl 1.21 * comparable</i> by the specified comparator: {@code comparator.compare(e1,
132     * e2)} must not throw a {@code ClassCastException} for any elements
133     * {@code e1} and {@code e2} in the set. If the user attempts to add
134 jsr166 1.12 * an element to the set that violates this constraint, the
135 jsr166 1.24 * {@code add} call will throw a {@code ClassCastException}.
136 jsr166 1.11 *
137     * @param comparator the comparator that will be used to order this set.
138 dl 1.21 * If {@code null}, the {@linkplain Comparable natural
139 jsr166 1.11 * ordering} of the elements will be used.
140     */
141     public TreeSet(Comparator<? super E> comparator) {
142 jsr166 1.27 this(new TreeMap<E,Object>(comparator));
143 dl 1.1 }
144    
145     /**
146 jsr166 1.12 * Constructs a new tree set containing the elements in the specified
147     * collection, sorted according to the <i>natural ordering</i> of its
148     * elements. All elements inserted into the set must implement the
149     * {@link Comparable} interface. Furthermore, all such elements must be
150 dl 1.21 * <i>mutually comparable</i>: {@code e1.compareTo(e2)} must not throw a
151     * {@code ClassCastException} for any elements {@code e1} and
152     * {@code e2} in the set.
153 jsr166 1.11 *
154     * @param c collection whose elements will comprise the new set
155 dl 1.21 * @throws ClassCastException if the elements in {@code c} are
156 jsr166 1.11 * not {@link Comparable}, or are not mutually comparable
157     * @throws NullPointerException if the specified collection is null
158 dl 1.1 */
159     public TreeSet(Collection<? extends E> c) {
160     this();
161     addAll(c);
162     }
163    
164     /**
165 jsr166 1.11 * Constructs a new tree set containing the same elements and
166     * using the same ordering as the specified sorted set.
167 dl 1.1 *
168 jsr166 1.11 * @param s sorted set whose elements will comprise the new set
169     * @throws NullPointerException if the specified sorted set is null
170 dl 1.1 */
171     public TreeSet(SortedSet<E> s) {
172     this(s.comparator());
173 jsr166 1.27 addAll(s);
174 dl 1.1 }
175    
176     /**
177 jsr166 1.13 * Returns an iterator over the elements in this set in ascending order.
178 dl 1.1 *
179 jsr166 1.13 * @return an iterator over the elements in this set in ascending order
180 dl 1.1 */
181     public Iterator<E> iterator() {
182 dl 1.21 return m.navigableKeySet().iterator();
183 dl 1.1 }
184    
185     /**
186 jsr166 1.13 * Returns an iterator over the elements in this set in descending order.
187 dl 1.1 *
188 jsr166 1.13 * @return an iterator over the elements in this set in descending order
189 jsr166 1.17 * @since 1.6
190 dl 1.1 */
191     public Iterator<E> descendingIterator() {
192 jsr166 1.27 return m.descendingKeySet().iterator();
193 dl 1.1 }
194    
195     /**
196 dl 1.21 * @since 1.6
197     */
198     public NavigableSet<E> descendingSet() {
199 jsr166 1.27 return new TreeSet(m.descendingMap());
200 dl 1.21 }
201    
202     /**
203 dl 1.1 * Returns the number of elements in this set (its cardinality).
204     *
205 jsr166 1.11 * @return the number of elements in this set (its cardinality)
206 dl 1.1 */
207     public int size() {
208 jsr166 1.27 return m.size();
209 dl 1.1 }
210    
211     /**
212 dl 1.21 * Returns {@code true} if this set contains no elements.
213 dl 1.1 *
214 dl 1.21 * @return {@code true} if this set contains no elements
215 dl 1.1 */
216     public boolean isEmpty() {
217 jsr166 1.27 return m.isEmpty();
218 dl 1.1 }
219    
220     /**
221 dl 1.21 * Returns {@code true} if this set contains the specified element.
222     * More formally, returns {@code true} if and only if this set
223     * contains an element {@code e} such that
224 jsr166 1.23 * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>.
225 dl 1.1 *
226 jsr166 1.16 * @param o object to be checked for containment in this set
227 dl 1.21 * @return {@code true} if this set contains the specified element
228 dl 1.1 * @throws ClassCastException if the specified object cannot be compared
229 jsr166 1.11 * with the elements currently in the set
230 jsr166 1.15 * @throws NullPointerException if the specified element is null
231     * and this set uses natural ordering, or its comparator
232     * does not permit null elements
233 dl 1.1 */
234     public boolean contains(Object o) {
235 jsr166 1.27 return m.containsKey(o);
236 dl 1.1 }
237    
238     /**
239     * Adds the specified element to this set if it is not already present.
240 dl 1.21 * More formally, adds the specified element {@code e} to this set if
241     * the set contains no element {@code e2} such that
242 jsr166 1.23 * <tt>(e==null&nbsp;?&nbsp;e2==null&nbsp;:&nbsp;e.equals(e2))</tt>.
243 jsr166 1.16 * If this set already contains the element, the call leaves the set
244 dl 1.21 * unchanged and returns {@code false}.
245 dl 1.1 *
246 jsr166 1.11 * @param e element to be added to this set
247 dl 1.21 * @return {@code true} if this set did not already contain the specified
248 jsr166 1.11 * element
249 dl 1.1 * @throws ClassCastException if the specified object cannot be compared
250 jsr166 1.16 * with the elements currently in this set
251 jsr166 1.15 * @throws NullPointerException if the specified element is null
252     * and this set uses natural ordering, or its comparator
253     * does not permit null elements
254 dl 1.1 */
255 jsr166 1.7 public boolean add(E e) {
256 jsr166 1.27 return m.put(e, PRESENT)==null;
257 dl 1.1 }
258    
259     /**
260     * Removes the specified element from this set if it is present.
261 dl 1.21 * More formally, removes an element {@code e} such that
262 jsr166 1.23 * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>,
263 dl 1.21 * if this set contains such an element. Returns {@code true} if
264 jsr166 1.16 * this set contained the element (or equivalently, if this set
265     * changed as a result of the call). (This set will not contain the
266     * element once the call returns.)
267 dl 1.1 *
268 jsr166 1.11 * @param o object to be removed from this set, if present
269 dl 1.21 * @return {@code true} if this set contained the specified element
270 dl 1.1 * @throws ClassCastException if the specified object cannot be compared
271 jsr166 1.16 * with the elements currently in this set
272 jsr166 1.15 * @throws NullPointerException if the specified element is null
273     * and this set uses natural ordering, or its comparator
274     * does not permit null elements
275 dl 1.1 */
276     public boolean remove(Object o) {
277 jsr166 1.27 return m.remove(o)==PRESENT;
278 dl 1.1 }
279    
280     /**
281     * Removes all of the elements from this set.
282 jsr166 1.11 * The set will be empty after this call returns.
283 dl 1.1 */
284     public void clear() {
285 jsr166 1.27 m.clear();
286 dl 1.1 }
287    
288     /**
289     * Adds all of the elements in the specified collection to this set.
290     *
291 jsr166 1.14 * @param c collection containing elements to be added to this set
292 dl 1.21 * @return {@code true} if this set changed as a result of the call
293 dl 1.1 * @throws ClassCastException if the elements provided cannot be compared
294 jsr166 1.11 * with the elements currently in the set
295     * @throws NullPointerException if the specified collection is null or
296     * if any element is null and this set uses natural ordering, or
297     * its comparator does not permit null elements
298 dl 1.1 */
299     public boolean addAll(Collection<? extends E> c) {
300     // Use linear-time version if applicable
301     if (m.size()==0 && c.size() > 0 &&
302 jsr166 1.27 c instanceof SortedSet &&
303 dl 1.1 m instanceof TreeMap) {
304 jsr166 1.9 SortedSet<? extends E> set = (SortedSet<? extends E>) c;
305 dl 1.1 TreeMap<E,Object> map = (TreeMap<E, Object>) m;
306 jsr166 1.9 Comparator<? super E> cc = (Comparator<? super E>) set.comparator();
307 dl 1.1 Comparator<? super E> mc = map.comparator();
308     if (cc==mc || (cc != null && cc.equals(mc))) {
309     map.addAllForTreeSet(set, PRESENT);
310     return true;
311     }
312     }
313     return super.addAll(c);
314     }
315    
316     /**
317 jsr166 1.11 * @throws ClassCastException {@inheritDoc}
318 dl 1.21 * @throws NullPointerException if {@code fromElement} or {@code toElement}
319     * is null and this set uses natural ordering, or its comparator
320     * does not permit null elements
321 jsr166 1.11 * @throws IllegalArgumentException {@inheritDoc}
322 jsr166 1.17 * @since 1.6
323 dl 1.1 */
324 dl 1.22 public NavigableSet<E> subSet(E fromElement, boolean fromInclusive,
325     E toElement, boolean toInclusive) {
326 jsr166 1.27 return new TreeSet<E>(m.subMap(fromElement, fromInclusive,
327 dl 1.22 toElement, toInclusive));
328 dl 1.1 }
329    
330     /**
331 jsr166 1.11 * @throws ClassCastException {@inheritDoc}
332 dl 1.21 * @throws NullPointerException if {@code toElement} is null and
333 jsr166 1.11 * this set uses natural ordering, or its comparator does
334     * not permit null elements
335     * @throws IllegalArgumentException {@inheritDoc}
336 jsr166 1.17 * @since 1.6
337 dl 1.1 */
338 dl 1.22 public NavigableSet<E> headSet(E toElement, boolean inclusive) {
339 jsr166 1.27 return new TreeSet<E>(m.headMap(toElement, inclusive));
340 dl 1.1 }
341    
342     /**
343 jsr166 1.11 * @throws ClassCastException {@inheritDoc}
344 dl 1.21 * @throws NullPointerException if {@code fromElement} is null and
345 jsr166 1.11 * this set uses natural ordering, or its comparator does
346     * not permit null elements
347     * @throws IllegalArgumentException {@inheritDoc}
348 jsr166 1.17 * @since 1.6
349 dl 1.1 */
350 dl 1.22 public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
351 jsr166 1.27 return new TreeSet<E>(m.tailMap(fromElement, inclusive));
352 dl 1.3 }
353    
354     /**
355 jsr166 1.11 * @throws ClassCastException {@inheritDoc}
356 dl 1.21 * @throws NullPointerException if {@code fromElement} or
357     * {@code toElement} is null and this set uses natural ordering,
358 jsr166 1.11 * or its comparator does not permit null elements
359     * @throws IllegalArgumentException {@inheritDoc}
360 dl 1.3 */
361     public SortedSet<E> subSet(E fromElement, E toElement) {
362 jsr166 1.27 return subSet(fromElement, true, toElement, false);
363 dl 1.3 }
364    
365     /**
366 jsr166 1.11 * @throws ClassCastException {@inheritDoc}
367 dl 1.21 * @throws NullPointerException if {@code toElement} is null
368 jsr166 1.11 * and this set uses natural ordering, or its comparator does
369     * not permit null elements
370     * @throws IllegalArgumentException {@inheritDoc}
371 dl 1.3 */
372     public SortedSet<E> headSet(E toElement) {
373 jsr166 1.27 return headSet(toElement, false);
374 dl 1.3 }
375    
376     /**
377 jsr166 1.11 * @throws ClassCastException {@inheritDoc}
378 dl 1.21 * @throws NullPointerException if {@code fromElement} is null
379 jsr166 1.11 * and this set uses natural ordering, or its comparator does
380     * not permit null elements
381     * @throws IllegalArgumentException {@inheritDoc}
382 dl 1.3 */
383     public SortedSet<E> tailSet(E fromElement) {
384 jsr166 1.27 return tailSet(fromElement, true);
385 dl 1.1 }
386    
387     public Comparator<? super E> comparator() {
388     return m.comparator();
389     }
390    
391     /**
392 jsr166 1.11 * @throws NoSuchElementException {@inheritDoc}
393 dl 1.1 */
394     public E first() {
395     return m.firstKey();
396     }
397    
398     /**
399 jsr166 1.11 * @throws NoSuchElementException {@inheritDoc}
400 dl 1.1 */
401     public E last() {
402     return m.lastKey();
403     }
404    
405     // NavigableSet API methods
406    
407     /**
408 jsr166 1.11 * @throws ClassCastException {@inheritDoc}
409 jsr166 1.15 * @throws NullPointerException if the specified element is null
410     * and this set uses natural ordering, or its comparator
411     * does not permit null elements
412 jsr166 1.17 * @since 1.6
413 dl 1.1 */
414 jsr166 1.11 public E lower(E e) {
415     return m.lowerKey(e);
416 dl 1.1 }
417    
418     /**
419 jsr166 1.11 * @throws ClassCastException {@inheritDoc}
420 jsr166 1.15 * @throws NullPointerException if the specified element is null
421     * and this set uses natural ordering, or its comparator
422     * does not permit null elements
423 jsr166 1.17 * @since 1.6
424 dl 1.1 */
425 jsr166 1.11 public E floor(E e) {
426     return m.floorKey(e);
427 dl 1.1 }
428    
429     /**
430 jsr166 1.11 * @throws ClassCastException {@inheritDoc}
431 jsr166 1.15 * @throws NullPointerException if the specified element is null
432     * and this set uses natural ordering, or its comparator
433     * does not permit null elements
434 jsr166 1.17 * @since 1.6
435 dl 1.1 */
436 jsr166 1.11 public E ceiling(E e) {
437     return m.ceilingKey(e);
438 dl 1.1 }
439    
440     /**
441 jsr166 1.11 * @throws ClassCastException {@inheritDoc}
442 jsr166 1.15 * @throws NullPointerException if the specified element is null
443     * and this set uses natural ordering, or its comparator
444     * does not permit null elements
445 jsr166 1.17 * @since 1.6
446 dl 1.1 */
447 jsr166 1.7 public E higher(E e) {
448     return m.higherKey(e);
449 dl 1.1 }
450    
451 jsr166 1.17 /**
452     * @since 1.6
453     */
454 dl 1.1 public E pollFirst() {
455     Map.Entry<E,?> e = m.pollFirstEntry();
456     return (e == null)? null : e.getKey();
457     }
458    
459 jsr166 1.17 /**
460     * @since 1.6
461     */
462 dl 1.1 public E pollLast() {
463     Map.Entry<E,?> e = m.pollLastEntry();
464     return (e == null)? null : e.getKey();
465     }
466    
467     /**
468 dl 1.21 * Returns a shallow copy of this {@code TreeSet} instance. (The elements
469 dl 1.1 * themselves are not cloned.)
470     *
471 jsr166 1.11 * @return a shallow copy of this set
472 dl 1.1 */
473     public Object clone() {
474     TreeSet<E> clone = null;
475 jsr166 1.27 try {
476     clone = (TreeSet<E>) super.clone();
477     } catch (CloneNotSupportedException e) {
478     throw new InternalError();
479     }
480 dl 1.1
481     clone.m = new TreeMap<E,Object>(m);
482     return clone;
483     }
484    
485     /**
486 dl 1.21 * Save the state of the {@code TreeSet} instance to a stream (that is,
487 dl 1.1 * serialize it).
488     *
489     * @serialData Emits the comparator used to order this set, or
490 dl 1.21 * {@code null} if it obeys its elements' natural ordering
491 jsr166 1.11 * (Object), followed by the size of the set (the number of
492     * elements it contains) (int), followed by all of its
493     * elements (each an Object) in order (as determined by the
494     * set's Comparator, or by the elements' natural ordering if
495 dl 1.1 * the set has no Comparator).
496     */
497     private void writeObject(java.io.ObjectOutputStream s)
498     throws java.io.IOException {
499 jsr166 1.27 // Write out any hidden stuff
500     s.defaultWriteObject();
501 dl 1.1
502     // Write out Comparator
503     s.writeObject(m.comparator());
504    
505     // Write out size
506     s.writeInt(m.size());
507    
508 jsr166 1.27 // Write out all elements in the proper order.
509     for (Iterator i=m.keySet().iterator(); i.hasNext(); )
510 dl 1.1 s.writeObject(i.next());
511     }
512    
513     /**
514 dl 1.21 * Reconstitute the {@code TreeSet} instance from a stream (that is,
515 dl 1.1 * deserialize it).
516     */
517     private void readObject(java.io.ObjectInputStream s)
518     throws java.io.IOException, ClassNotFoundException {
519 jsr166 1.27 // Read in any hidden stuff
520     s.defaultReadObject();
521 dl 1.1
522     // Read in Comparator
523 jsr166 1.9 Comparator<? super E> c = (Comparator<? super E>) s.readObject();
524 dl 1.1
525     // Create backing TreeMap
526 jsr166 1.27 TreeMap<E,Object> tm;
527     if (c==null)
528     tm = new TreeMap<E,Object>();
529     else
530     tm = new TreeMap<E,Object>(c);
531     m = tm;
532 dl 1.1
533     // Read in size
534     int size = s.readInt();
535    
536     tm.readTreeSet(size, s, PRESENT);
537     }
538    
539     private static final long serialVersionUID = -2479143000061671589L;
540     }